Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 262
tjwrona1992 Avatar asked May 05 '15 20:05

tjwrona1992


1 Answers

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

is the same as

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

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

like image 147
choroba Avatar answered Oct 21 '22 03:10

choroba