曲径通幽论坛

标题: 命令行参数之 -p 选项 -- 循环执行命令(强制打印) [打印本页]

作者: beyes    时间: 2012-7-18 22:32
标题: 命令行参数之 -p 选项 -- 循环执行命令(强制打印)
-p 选项和 -n  选项的功能类似,但是它还提供了个强制打印的功能,它的作用是如下代码的缩写:
[code=perl]LINE:
    while (<>) {
      # your code goes here
    } continue {
      print or die "-p destination: $!\n";
    }[/mw_shl_code]
上面代码中,LINE 是该段程序的一个标记。while 负责从标准输入里读入每行,被读入的行的内容是存储在预定义变量 $_ 中的。在 continue 代码块里,正是一个 print 语句,强制打印了读入的每行内容,确切的说,是打印 $_ 的内容。

如下测试文本:
$ cat tmp.txt
hello world
hello linux
hello perl
good perler
best linuxer
strong unixer
weak windower
运行输出:
[beyes@beyes   command]$ perl -p -e '$_ = "$. - $_"' <tmp.txt
1 - hello world
2 - hello linux
3 - hello perl
4 - good perler
5 - best linuxer
6 - strong unixer
7 - weak windower
在上面的命令中,如果你不使用 -p ,那么不会打印出这些内容,除非在命令中使用了 print 函数,因此在使用 -p 选项时,print 是可省略的。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2