How to read STDIN into a variable in perl

2019-06-14 19:23发布

I want to read from STDIN and have everything in a variable, how can I do this?

标签: perl file stdin
2条回答
冷血范
2楼-- · 2019-06-14 19:48

This is probably not the most definitive way:

my $stdin = join("", <STDIN>);

Or you can enable slurp mode and get the whole file in one go:

local $/;
my $stdin = <STDIN>;

[but see man perlvar for caveats about making global changes to special variables]

If instead of a scalar you want an array with one element per line:

my @stdin = <STDIN>;
查看更多
ゆ 、 Hurt°
3楼-- · 2019-06-14 19:53
my $var = do { local $/; <> };

This doesn't quite read Stdin, it also allows files to specify on the command line for processing (like sed or grep).

This does include line feeds.

查看更多
登录 后发表回答