【发布时间】:2011-09-17 12:50:13
【问题描述】:
在编写传统的 Unix/Linux 程序时,perl 提供了菱形运算符 。我正在尝试了解如何测试是否根本没有传递任何参数,以避免 perl 脚本在 STDIN 不应该时处于等待循环中。
#!/usr/bin/perl
# Reading @ARGV when pipe or redirect on the command line
use warnings;
use strict;
while ( defined (my $line = <ARGV>)) {
print "$ARGV: $. $line" if ($line =~ /eof/) ; # an example
close(ARGV) if eof;
}
sub usage {
print << "END_USAGE" ;
Usage:
$0 file
$0 < file
cat file | $0
END_USAGE
exit();
}
一些输出运行表明 有效,但没有参数我们等待 STDIN 输入,这不是我想要的。
$ cat grab.pl | ./grab.pl
-: 7 print "$ARGV: $. $line" if ($line =~ /eof/) ; # an example
-: 8 close(ARGV) if eof;
$ ./grab.pl < grab.pl
-: 7 print "$ARGV: $. $line" if ($line =~ /eof/) ; # an example
-: 8 close(ARGV) if eof;
$ ./grab.pl grab.pl
grab.pl: 7 print "$ARGV: $. $line" if ($line =~ /eof/) ; # an example
grab.pl: 8 close(ARGV) if eof;
$ ./grab.pl
^C
$ ./grab.pl
[Ctrl-D]
$
首先想到的是测试 $#ARGV,它保存了@ARGV 中最后一个参数的编号。然后我在上面的脚本中添加了一个测试,在 while 循环之前,如下所示:
if ( $#ARGV < 0 ) { # initiated to -1 by perl
usage();
}
这并没有产生预期的结果。 $#ARGV 是 -1 用于命令行上的重定向和管道。使用此检查(grabchk.pl)运行,问题发生了变化,我无法通过管道或重定向案例中的 读取文件内容。
$ ./grabchk.pl grab.pl
grab.pl: 7 print "$ARGV: $. $line" if ($line =~ /eof/) ;
grab.pl: 8 close(ARGV) if eof;
$ ./grabchk.pl < grab.pl
Usage:
./grabchk.pl file
./grabchk.pl < file
cat file | ./grabchk.pl
$ cat grab.pl | ./grabchk.pl
Usage:
./grabchk.pl file
./grabchk.pl < file
cat file | ./grabchk.pl
有没有更好的测试来查找shell传递给perl的所有命令行参数?
【问题讨论】:
-
这是一个旁白,但当你可以写
if (@array == 0)或unless (@array)时,千万不要写if ($#array < 0)。当你想要“数组中元素的数量”时使用“数组中的最后一个索引”并不是你的意思。 -
我会记住这一点
标签: perl pipe argv diamond-operator