gpt4 book ai didi

linux - 通过管道将文件列表传递给 perl 脚本

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:57:42 25 4
gpt4 key购买 nike

我遇到一个问题,我的 perl 脚本在输入管道时会失败,但当我只是单独列出所有文件名时工作正常。

作为引用,perl 脚本的输入是用 while(<>) 读取的。

例子:

script.pl file1.tag file2.tag file3.tag

运行良好。

但是以下都失败了。

find ./*.tag | chomp | script.pl
ls -l *.tag | perl -pe 's/\n/ /g' | script.pl
find ./*.tag | perl -pe 's/\n/ /g' | script.pl

我还测试了将它转储到一个文本文件中并将其放入 perl 中:

cat files.text | script.pl

他们都以同样的方式失败。这就像脚本没有传递任何输入参数,程序刚刚结束。

最佳答案

来自 perldoc perlop :

The null filehandle <> is special [...] 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.

您没有将任何命令行参数传递给您的 Perl 脚本,因此您输入的所有内容都会被读入 STDIN而不是被视为文件名:

$ echo foo > foo.txt
$ echo bar > bar.txt
$ ls | perl -e 'print "<$_>\n" while <>'
<bar.txt
>
<foo.txt
>

注意文件 foo.txtbar.txt未实际阅读;我们得到的只是文件名。如果要打开和读取文件,则必须将它们作为命令行参数传递或显式设置 @ARGV :

$ perl -e 'print "<$_>\n" while <>' *
<bar
>
<foo
>

如果您有大量文件,您可能会从 find 获得, 你应该使用 xargs作为Dyno Hongjun Fu suggested .

但是,您不需要 find , ls , cat ,或者你的 Perl 单行代码在所有 .tag 上运行你的脚本当前目录下的文件。简单地做:

script.pl *.tag

关于linux - 通过管道将文件列表传递给 perl 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29042721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com