in reply to Need help with Piping

#!/usr/bin/perl -w use strict; my $var = ''; while(<>){ $var .= $_; } # Do stuff with $var

Replies are listed 'Best First'.
Re^2: Need help with Piping
by Skeeve (Parson) on Aug 13, 2008 at 06:47 UTC

    If I just want the STDIN (or any file content) in a variable, and don't like to loop, I usually use this idiom:

    my $var; SLURP: { local $/; $var= <>; }

    local-izing $/ in a block undefines it and so no $var gets the whole filecontent sithout looping and reassembling it line by line.


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
      I like Skeeve's solution. It is the best and clearest way to do this in Perl 5.

      For the sake of completeness: In Perl 6 the built-in way for this is simply:

      $var = slurp \*STDIN;

      This can also be done in Perl 5 by using the Perl6::Slurp module.

      You can do all of that in one line...

      my $var = do { local $/ ; <> };

      www.jasonkohles.com
      We're not surrounded, we're in a target-rich environment!