nev*_*int 2 unix linux bash perl stdin
我希望在bash中有这样的管道
#! /usr/bin/bash
cut -f1,2 file1.txt | myperl.pl foo | sort -u
Run Code Online (Sandbox Code Playgroud)
现在myperl.pl
它有这样的内容
my $argv = $ARG[0] || "foo";
while (<>) {
chomp;
if ($argv eq "foo") {
# do something with $_
}
else {
# do another
}
}
Run Code Online (Sandbox Code Playgroud)
但是为什么Perl脚本无法识别通过bash传递的参数?即代码打破此消息:
Can't open foo: No such file or directory at myperl.pl line 15.
Run Code Online (Sandbox Code Playgroud)
正确的方法是什么,以便我的Perl脚本可以同时接收标准输入和参数?
<>很特殊:它从标准输入或命令行中列出的每个文件返回行.因此,命令行中的参数被解释为要打开的文件名和从中返回行.因此错误消息无法打开文件foo.
在您的情况下,您知道要从中读取数据<stdin>,因此只需使用它而不是<>:
while(<stdin>)
Run Code Online (Sandbox Code Playgroud)
如果你想保留的可选的命令行上指定输入文件的功能,你需要删除的说法foo从@ARGV使用前<>:
my $firstarg = shift(@ARGV);
...
while (<>) {
...
if ($firstarg eq "foo") ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2143 次 |
| 最近记录: |