Bash 中的 Perl:如何同时从管道读取并将参数传递给 perl?

Perl inside Bash: How to read from pipe and pass arguments to perl at the same time?

以下是我正在尝试的代码:

echo "a b c" | perl -e 'print $ARGV[0]; print $ARGV[1]; print $_;' "abc" "def"

这段代码的输出是:

abcdef

我不明白为什么 "print $_;" 没有像往常一样打印 "a b c"。有什么想法吗?

您没有使用 -n-p,因此您没有使用 <> 作为标准输入。如果你有争论,你无论如何都不会这样做。

解释:

当您使用 -n-p 时,它会在您的代码周围放置一个 while(<>) 循环,如下所示:

perl -ne ' print ' 

等于

perl -e ' while (<>) { print }'

如果您使用 -p,则为:

perl -e ' while (<>) { print } continue { print $_ }'

在这个阶段,Perl 将通过检查 @ARGV 来决定 <> 将如何工作,脚本的参数存储在哪里。如果其中有任何内容,它会将参数视为文件名,并尝试打开并读取这些文件。文件句柄将被称为 ARGV。此时,<>不能用于从标准输入读取。

解决方案

换句话说,使用参数将覆盖 STDIN 中的读数。所以如果你想从标准输入读取,你可以使用那个文件句柄:

echo "a b c" | perl -e ' print @ARGV[0,1]; while (<STDIN>) { print } ' foo bar

另一种选择是事先清除 @ARGV 数组,如下所示:

echo "a b c"|perl -ne'BEGIN { @x = @ARGV; @ARGV = () }; print @x; print;' foo bar

但这也会在您的每行输入中打印一次 @x,这可能是不可取的。