Learning Perl: 5.4. Output to Standard Output

Previous Page

Next Page

 

5.4. Output to Standard Output

The print operator takes a list of values and sends each item (as a string,of course) to standard output in turn,one after another. It doesn't add any extra characters before,after,or in between the items.[*] If you want spaces between items and a newline at the end,you have to say so:

[*] Well,it doesn't add anything extra by default,but this default (like so many others in Perl) may be changed. Changing these defaults will likely confuse your maintenance programmer,so avoid doing so except in small,quick-and-dirty programs or (rarely) in a small section of a normal program. See the perlvar manpage to learn about changing the defaults.

    $name = "Larry Wall";
    print "Hello there,$name,did you know that 3+4 is ",3+4,"?/n";

Of course,that means printing an array and interpolating an array are different:

    print @array;     # print a list of items
    print "@array";   # print a string (containing an interpolated array)

The first print statement will print a list of items,one after another,with no spaces in between. The second one will print one item,which is the string you get by interpolating @array into the empty stringthat is,it prints the contents of @array,separated by spaces.[

] If @array holds qw/ fred barney betty /,[

]
the first one will print fredbarneybetty,and the second will print fred barney betty separated by spaces.

[

] Yes,the spaces are another default. See the perlvar manpage again.

[

] You know that we mean a three-element list here,right? This is just Perl notation.

But before you decide to use the second form all the time,imagine that @array is a list of unchomped lines of input. That is,imagine that each of its strings has a trailing newline character. Now,the first print statement prints fred,barney,and betty on three separate lines. But the second one prints this:

    fred
     barney
     betty

Do you see where the spaces come from? Perl is interpolating an array,so it puts spaces between the elements. We get the first element of the array (fred and a newline character),a space,the next element of the array (barney and a newline character),and the last element of the array (betty and a newline character). The result is that the lines seem to have become indented except for the first one. Every week or two,a message appears on the newsgroup comp.lang.perl.misc with a subject line like this:

Without reading the message,we know the program used double quotes around an array containing unchomped strings. When asked,"Did you perhaps put an array of unchomped strings inside double quotes?",the answer is always yes.

Generally,if your strings contain newlines,you'll simply want to print them:

    print @array;

But if they don't contain newlines,you'll generally want to add one at the end:

    print "@array/n";

If you're using the quote marks,you'll generally be adding the /n at the end of the string anyway; this should help you to remember which is which.

It's normal for your program's output to be buffered. Instead of sending out every little bit of output immediately,it'll be saved until there's enough to bother with. If (for example) you're going to save the output to disk,it would be (relatively) slow and inefficient to spin the disk every time you add one or two characters to the file. Generally,then,the output will go into a buffer that is flushed (that is,actually written to disk or wherever) only when the buffer gets full or when the output is otherwise finished (such as at the end of runtime). Usually,that's what you want.

But if you (or a program) are waiting impatiently for the output,you may wish to take that performance hit and flush the output buffer each time you print. See the Perl manpages for more information on controlling buffering.

Since print is looking for a list of strings to print,its arguments are evaluated in list context. Since the diamond operator (as a special kind of line-input operator) will return a list of lines in a list context,these can work well together:

    print <>;          # source code for 'cat'

    print sort <>;     # source code for 'sort'

To be fair,the standard Unix commands cat and sort do have some additional functionality that these replacements lack,but you can't beat them for the price! You can now reimplement all of your standard Unix utilities in Perl and painlessly port them to any machine that has Perl whether that machine is running Unix or not. And you can be certain that the programs on every different type of machine will have the same behavior.[*]

[*] In fact,the Perl Power Tools (PPT) project,whose goal is to implement all of the classic Unix utilities in Perl,completed nearly all the utilities (and most of the games) but got bogged down when they got to reimplementing the shell. The PPT project has been useful because it has made these standard utilities available on many non-Unix machines.

What might not be obvious is that print has optional parentheses,which can sometimes cause confusion. Remember the rule that parentheses in Perl may be omitted except when doing so would change the meaning of a statement. Here are two ways to print the same thing:

    print("Hello,world!/n");
    print "Hello,world!/n";

So far,so good. Another rule in Perl is that if the invocation of print looks like a function call,then it is a function call. It's a simple rule,but what does it mean for something to look like a function call?

In a function call,there's a function name immediately[*] followed by parentheses around the function's arguments,like this:

[*] We say "immediately" here because Perl won't permit a newline character between the function name and the open parenthesis in this kind of function call. If there is a newline there,Perl will see your code as making a list operator,rather than a function call. This is the kind of technical detail that we mention for completeness. If you're terminally curious,see the full story in the manpages.

    print (2+3);

That looks like a function call,so it is a function call. It prints 5,but then it returns a value like any other function. The return value of print is a true or false value,indicating the success of the print. It nearly always succeeds unless you get some I/O error,so the $result in the following statement will normally be 1:

    $result = print("hello world!/n");

But what if you used the result in some other way? Suppose you decide to multiply the return value times four:

    print (2+3)*4;  # Oops!

When Perl sees this line of code,it prints 5 as you asked. Then it takes the return value from print,which is 1,and multiplies that times 4. Then,it throws away the product,wondering why you didn't tell it to do something else with it. At this point,someone looking over your shoulder says,"Hey,Perl can't do math! That should have printed 20,rather than 5!"

This is the problem with the optional parentheses; sometimes,we humans forget where the parentheses belong. When there are no parentheses,print is a list operator,printing all of the items in the following list,which is what you'd expect. But when the first thing after print is a open parenthesis,print is a function call,and it will print only what's found inside the parentheses. Since that line had parentheses,it's the same to Perl as if you'd said this:

    ( print(2+3) ) * 4;  # Oops!

Fortunately,Perl can almost always help you with this if you ask for warnings. So use -w,or use warnings,at least during program development and debugging.

This ruleIf it looks like a function call,it is a function callapplies to all list functions[

] in Perl,not just to print,but you're most likely to notice it with print. If print (or another function name) is followed by an open parenthesis,ensure the corresponding closed parenthesis comes after all of the arguments to that function.

[

] Functions that take zero or one arguments don't suffer from this problem.

Previous Page

Next Page

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(&lt;&gt;){ chomp; print &quot;$_n&quot; unless
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据进行拼凑,然后将拼凑后的数据用“|”连接在一起。表格内容如下: 员工号码员工姓名职位入职日期1001张三销售1980/12/17 0:00:
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,还不能保证书写一定正确。写了个Perl脚本,可快速构造MySQL脚本语句。脚本如下:#!/usr/bin/perluse strict;m
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了一个表的数据量统计日报,主要是针对数据库中使用较频繁,数据量又较大的31张表。该日报有两个sheet组成,第一个sheet是数据填写,第二个sh
在实际生产环境中,常常需要从后台日志中截取报文,报文的形式类似于.........一个后台日志有多个报文,每个报文可由操作流水唯一确定。以前用AWK写过一个,程序如下:beginline=`awk &
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让人领略到perl正则表达式的强大,程序如下:#!/usr/bin/perluse strict;my (%hash,%hash1,@arra
忍不住在 PerlChina 邮件列表中盘点了一下 Perl 里的 Web 应用框架(巧的是 PerlBuzz 最近也有一篇相关的讨论帖),于是乎,决定在我自己的 blog 上也贴一下 :) 原生 CGI/FastCGI 的 web app 对于较小的应用非常合适,但稍复杂一些就有些痛苦,但运行效率是最高的 ;) 如果是自己用 Perl 开发高性能的站,多推荐之。 Catalyst, CGI::A
bless有两个参数:对象的引用、类的名称。 类的名称是一个字符串,代表了类的类型信息,这是理解bless的关键。 所谓bless就是把 类型信息 赋予 实例变量。 程序包括5个文件: person.pm :实现了person类 dog.pm :实现了dog类 bless.pl : 正确的使用bless bless.wrong.pl : 错误的使用bless bless.cc : 使用C++语言实
gb2312转Utf的方法: use Encode; my $str = "中文"; $str_cnsoftware = encode("utf-8", decode("gb2312", $str));   Utf转 gb2312的方法: use Encode; my $str = "utf8中文"; $str_cnsoftware = encode("gb2312", decode("utf-8
  perl 计算硬盘利用率, 以%来查看硬盘资源是否存在IO消耗cpu资源情况; 部份代码参考了iostat源码;     #!/usr/bin/perl use Time::HiRes qw(gettimeofday); use POSIX; $SLEEPTIME=3; sub getDiskUtl() { $clock_ticks = POSIX::sysconf( &POSIX::_SC_
1 简单变量 Perl 的 Hello World 是怎么写的呢?请看下面的程序: #!/usr/bin/perl print "Hello World" 这个程序和前面 BASH 的 Hello World 程序几乎相同,只是第一行换成了 #!/usr/bin/perl ,还有显示的时候用的是 print,而不是 echo。有了前面 BASH 基础和 C 语言的基础,许多 Perl 的知识可以很
本文介绍Perl的Perl的简单语法,包括基本输入输出、分支循环控制结构、函数、常用系统调用和文件操作,以及进程管理几部分。 1 基本输入输出 在 BASH 脚本程序中,我们用 read var 来实现从键盘的输入,用 echo $var 来实现输出。那么在 Perl 中将有一点变化。Perl 中将标准输入用关键词 表示;标准输出用 表示,标准错误输出用 表示。故而从标准输入读取数据可以写成: $
正则表达式是 Perl 语言的一大特色,也是 Perl 程序中的一点难点,不过如果大家能够很好的掌握他,就可以轻易地用正则表达式来完成字符串处理的任务,当然在 CGI 程序设计中就更能得心应手了。下面我们列出一些正则表达式书写时的一些基本语法规则。 1 正则表达式的三种形式 首先我们应该知道 Perl 程序中,正则表达式有三种存在形式,他们分别是: 匹配:m/<regexp>/ (还可以简写为 /
在学习Perl和Shell时,有很多人可能会问这样一个问题,到底先学习哪个或者学习哪个更好! 每个人都有自己的想法,以下是个人愚见,请多多指教! Perl是larry wall为解决日常工作中的一个编程问题而产生的,它最初的主要功能是用于分析基于文本的数据和生成这些数据的统计和结果;尽管初衷很简单,但是后来发展了很多特点: 1、Perl是一种借鉴了awk、C、sed、shell、C++、Java等
Perl 有很多命令行参数. 通过它, 我们有机会写出更简单的程序. 在这篇文章里我们来了解一些常用的参数. (重点提示:在window下执行命令行程序的方式为 : perl -e "some code", 注意:是双引号啊,不是单引号,linux下执行时单引号) Safety Net Options 在使用 Perl 尝试一些聪明( 或 stupid) 的想法时, 错误难免会发生. 有经验的 P
转自: http://bbs.chinaunix.net/thread-1191868-1-1.html# 让你的perl代码看起来更像perl代码,而不是像C或者BASIC代码,最好的办法就是去了解perl的内置变量。perl可以通过这些内置变量可以控制程序运行时的诸多方面。 本文中,我们一起领略一下众多内置变量在文件的输入输出控制上的出色表现。 行计数 我决定写这篇文章的一个原因就是,当我发现
2009-02-02 13:07 #!/usr/bin/perl # D.O.M TEAM - 2007 # anonyph; arp; ka0x; xarnuz # 2005 - 2007 # BackConnectShell + Rootlab t00l # priv8! # 3sk0rbut0@gmail.com # # Backconnect by data cha0s (modifica
转自: http://bbs.chinaunix.net/thread-1191868-1-1.html# 让你的perl代码看起来更像perl代码,而不是像C或者BASIC代码,最好的办法就是去了解perl的内置变量。perl可以通过这些内置变量可以控制程序运行时的诸多方面。 本文中,我们一起领略一下众多内置变量在文件的输入输出控制上的出色表现。 行计数 我决定写这篇文章的一个原因就是,当我发现
黑莓 手机 屏幕发展历程对比 blackberry 各型号屏幕大小   黑莓手 机 一直在不断发展且新机型 也在不断上市. 因此,不同黑莓机型的屏幕分辨率也在不断变化着. 总的来说,屏幕分辨率一直在提高并且越来越清晰.我们对所有的黑莓 机型的屏幕分辨率做了个对比.~51blackberry ~com     可能大家特别感兴趣是新发布的黑莓机型,它的分辨率也是黑莓 机型中前所未有的.   黑莓 b
      公司里没有我用惯的UltraEdit的lisence了, 只能无奈转向开源的Notepad++, 找了半天才知道配置运行Perl的办法。         1,用Notepad++打开.pl文件,         2, F5或者Run->Run,打开运行窗口,在下面的框框里输入:Perl -w "$(FULL_CURRENT_PATH)", 然后Save,保存成一个命令就行,名字比如叫R