How to read STDIN into a variable in perl

牧云@^-^@ 提交于 2020-01-03 06:33:46

问题


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


回答1:


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>;



回答2:


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.



来源:https://stackoverflow.com/questions/34421644/how-to-read-stdin-into-a-variable-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!