2

I had a look at the source of Slurp and I would love to understand how does slurp() work:

sub slurp { 
    local( $/, @ARGV ) = ( wantarray ? $/ : undef, @_ ); 
    return <ARGV>;
}

Where is the file even opened?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
David B
  • 29,258
  • 50
  • 133
  • 186
  • Related http://stackoverflow.com/q/206661/100754 and http://stackoverflow.com/questions/2213485/how-do-i-read-a-files-contents-into-a-perl-scalar I don't see any reason to use this module. – Sinan Ünür Oct 25 '10 at 11:06

3 Answers3

6

See ARGV and $/ in perldoc perlvar.

See also Path::Class:File::slurp.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
  • Note that File::Slurp is now considered broken since it doesn't know what to do with encodings, and it's slow. See http://blogs.perl.org/users/leon_timmermans/2013/05/why-you-dont-need-fileslurp.html – brian d foy Sep 19 '14 at 23:30
  • @briandfoy I have grown really fond of [Path::Class](https://metacpan.org/pod/Path::Class) and changed my recommendation to reflect that. – Sinan Ünür Sep 21 '14 at 01:44
5

ARGV is a handle, the file has been opened implicitly.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
daxim
  • 39,270
  • 4
  • 65
  • 132
1

This snippet puts the filename in @ARGV. The ARGV filehandle implicitly opens the files it sees in @ARGV. This is the same filehandle that we don't see in the diamond operator <> since it's the default filehandle for that operator.

This is the same Perl idiom as:

 my $data = do { local( @ARGV, $/ ) = $file; <> };
brian d foy
  • 129,424
  • 31
  • 207
  • 592