2010-02-26 52 views
6

考虑以下傻Perl程序:如何在Perl中为<>混合命令行参数和文件名?

$firstarg = $ARGV[0]; 

print $firstarg; 

$input = <>; 

print $input; 

我从终端运行,如:

perl myprog.pl sample_argument 

而得到这个错误:

Can't open sample_argument: No such file or directory at myprog.pl line 5. 

任何想法,这是为什么?当它到达<>它试图从(不存在的)文件中读取“sample_argument”或什么?为什么?

回答

12

<>是简写形式,“从@ARGV指定的文件中读取,或者如果@ARGV是空的,然后从STDIN读”。在您的程序中,@ARGV包含值("sample_argument"),因此当您使用<>运算符时,Perl会尝试从该文件读取数据。

$firstarg = shift @ARGV; 
print $firstarg; 
$input = <>;  # now @ARGV is empty, so read from STDIN 
print $input; 
+2

啊哈!更改为工作正常:) – Jimmeh 2010-02-26 21:31:52

1

默认情况下,perl使用命令行参数作为<>的输入文件。你已经使用过之后,你应该自己消耗他们shift;

+0

你有它向后。在默认情况下,Perl不会对'@ ARGV'执行任何操作。这是'<>'特别的行为。 – 2010-02-26 22:15:23

+0

这就是我所说的。那个<>使用@ARGV,除非你自己用shift来使用它们。 – 2010-02-26 22:26:59

8

见PerlIO的手册页,其中部分内容如下:

The null filehandle <> is special: it can be used to emulate the behavior of sed and awk. Input from <> comes either from standard input, or from each file listed on the command line. Here’s how it works: the first time <> is evaluated, the @ARGV array is checked, and if it is empty, $ARGV[0] is set to "-", which when opened gives you standard input. The @ARGV array is then processed as a list of filenames.

如果你想STDIN,使用

您可以通过清除@ARGV你到<>线之前将其修复STDIN,而不是<>

相关问题