jcubic
jcubic

Reputation: 66480

How to read STDIN into a variable in perl

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

I'm know know almost nothing about Perl, and needed to create CGI script to read data from POST request, and was not able to find anything how to do that.

Upvotes: 3

Views: 7538

Answers (2)

Sobrique
Sobrique

Reputation: 53478

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.

Upvotes: 3

Alnitak
Alnitak

Reputation: 339786

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

Upvotes: 8

Related Questions