News for hackers. Stuff that matters.
Re:Python for Perl programmers by tocomment on Tuesday April 03, 2012 @02:25PM (#3794142)
I ended up going with this one for better or worse. I'm afraid I still don't quite understand it:

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

Re:Python for Perl programmers by abuzzooz on Tuesday April 03, 2012 @02:47PM (#3794226)
If you don't understand it, why use it? Is it that important for you to do this in one line of (relatively obscured) code, than in 2-3 lines of readable code?

For the record, the do() block defines @ARGV (which normally holds the command-line arguments) to contain the value of the $file (presumably a file name), and sets $/ (which is the input record separator) to an undefined value. In Perl, <> is synonymous to <STDIN> which makes it read from stdin. Since @ARGV now contains a file name, Perl will open this file for reading. Since $/ is undefined, Perl will enter in "slurp" mode, and will gobble up the whole file in one shot. Since this is the last statement in the do() block, it will be returned as its value, and stored in $text.

Lots of Perl magic happening here. I advise you against using such shortcuts.

Re:Python for Perl programmers by lawn on Tuesday April 03, 2012 @03:07PM (#3794306)
my $txt = do { local $/ = <$file>; };

or

my $txt = do { local $/; <$file>; };

are as I know the preferred ways to do it. As a previous comment explained, $/ is the record separator and when you localize it it's value is set to undef. Which means we read the whole filehandle (the second part). As a do block evaluates to the value of the last expression, the contents of the file is the result of the whole expression.

If you're serious about Perl I recommend Modern Perl which is a 250 page really good introduction for the language, intended for programmers.

Re:Python for Perl programmers by sciurus on Tuesday April 03, 2012 @03:07PM (#3794307)
Agreed, the trick with a local ARGV and the null filehandle is too clever. Don't copy code you don't understand! I think opening the file is much clearer.

    open( my $fh, '<', $file ) or die "cannot open $file\n";
    my $text = do { local( $/ ) ; <$fh> } ;

  http://perldoc.perl.org/perlopentut.html
  http://perldoc.perl.org/functions/do.html
  http://perldoc.perl.org/functions/local.html
  http://perldoc.perl.org/perlop.html#I%2fO-Operators
Re:Python for Perl programmers by mdda on Tuesday April 03, 2012 @02:42PM (#3794207)
The local $/ is the trick : It reset the line-end character to 'undef', which makes the <> line-slurp the whole file at once.