2010-02-26 33 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,而不是<>

相關問題