3

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.

jcubic
  • 61,973
  • 54
  • 229
  • 402
  • 3
    Presuming that you know how to assign to variables and read STDIN, I imagine you're having some other unspecified problem. Are you trying to read to EOF (list context)? Are you reading from a pipe that does not close? Are you reading from a Terminal? – tjd Dec 22 '15 at 18:13
  • Related: https://stackoverflow.com/questions/953707/in-perl-how-can-i-read-an-entire-file-into-a-string – user202729 Oct 30 '18 at 16:34

2 Answers2

8

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>;
ikegami
  • 367,544
  • 15
  • 269
  • 518
Alnitak
  • 334,560
  • 70
  • 407
  • 495
3
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.

Sobrique
  • 52,974
  • 7
  • 60
  • 101