tjwrona1992 tjwrona1992 - 8 months ago 27
Perl Question

Fancy file slurping in Perl

I was looking into efficient ways to read files in Perl and came across this very interesting one liner:

my $text = do { local (@ARGV, $/) = $file; <> };

My question is: How exactly does this work? Normally when slurping a file you set
$/ = undef
, but I don't see how this does that. This little piece of code is proving to be very difficult to wrap my head around.

What would be a simplified breakdown and explanation for this?

Now that I know how it works, lets get real fancy!

Not that this code has any real use; it's just fun to figure out and cool to look at. Here is a one-liner to slurp multiple files at the same time!!!

my @texts = map { local (@ARGV, $/) = $_; <> } @files;

local (@ARGV, $/) = $file;

is the same as

local @ARGV = ( $file );
local $/    = undef;

<> then reads from files mentioned in @ARGV, i.e. from $file.