问题
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