9

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;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tjwrona1992
  • 8,614
  • 8
  • 35
  • 98
  • 1
    perl allows to assign multiple variables in a single assignment (don't know how it's properly called): `($a, $b, $c) = (1, 2)`. `$c` here would end up `undef` – n0rd May 05 '15 at 20:22
  • 3
    That is horrible. You have to ask what it does, so don't duplicate it – Borodin May 05 '15 at 20:32
  • 1
    This line of code actually appears to be a commonly used piece of Perl code. I've seen it in more than one place which is what lead me to ask this question. – tjwrona1992 May 05 '15 at 20:33
  • 1
    That's what horrible about it... ;-) Perl is full of these neat little shortcuts that are too horrible to use and too neat not to... – alexis May 06 '15 at 15:25
  • 3
    Don't need `map` for multiple files. `my @texts = do { local (@ARGV, $/) = @files; <> };` – ikegami May 06 '15 at 18:40
  • 1
    (>\*o\*)> *\*mind blown\** <(\*o\*<) – tjwrona1992 May 06 '15 at 18:45

1 Answers1

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

is the same as

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

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

choroba
  • 231,213
  • 25
  • 204
  • 289
  • 1
    Oh, that makes sense, then the `do {}` just returns whatever the value of the last evaluated expression is, which would be the value of `<>` or the contents of the file. Thanks @charoba! – tjwrona1992 May 06 '15 at 12:37
  • @jwrona1992, The point of `do` is to limit the scope in which `@ARGV` and `$/` are changed. – ikegami May 06 '15 at 18:41