perl How to read command line argument as if it's file content

时间:2019-04-17 01:07:37

标签: file perl command-line

I have a function that takes in filename and prints the content of the file

#test.pl
while (<>) {
    print $_;
}
exit(0);

I want to run this on the command line except instead of a filename I want to use the actual content as parameter without changing the script, similarly to an anonymous FIFO (e.g. "<(...)" operator in shell) to substitute a filename string with it's content?

1 个答案:

答案 0 :(得分:2)

这是一个shell问题,但您没有指定哪个shell。

sh

最简单的方法是将数据直接传递到STDIN。

printf 'foo bar' | test.pl

printf 'foo\nbar\n' | test.pl

test.pl <<'.'
foo
bar
.

重击

除了sh的解决方案之外,您还可以使用以下方法:

test.pl <<<'foo bar'

test.pl <<<$'foo\nbar\n'

test.pl <( printf 'foo\nbar\n' )

最后一个避免使用STDIN。 (在内部)这比其他解决方案要复杂,但是它允许您传递多个“虚拟文件”。