Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: Any downsides to this slurp idiom? (updated)

by haukex (Archbishop)
on Jun 30, 2018 at 19:34 UTC ( #1217663=note: print w/replies, xml ) Need Help??

in reply to Any downsides to this slurp idiom?

Thanks everyone for your replies! :-) For completeness, here are some slurping examples, incorporating various suggestions:

  • The basic version (with the improved error message first suggested by haj):
    my $data = do { open my $fh, '<', $file or die "$file: $!"; local $/; <$fh> };
  • Opening a file with an encoding (in this case UTF-8):
    my $data = do { open my $fh, '<:raw:encoding(UTF-8)', $file or die "$file: $!"; local $/; <$fh> };
  • A version that should use less memory, suggested by BrowserUk (see this discussion - Copy-On-Write, available in newer Perls, may take care of this):
    my $data; { open my $fh, '<', $file or die "$file: $!"; local $/; $data = <$fh> };
  • This short version, first suggested by tybalt89, however, note that as opposed to the above examples, this does not die but only emits a warning if the file could not be opened (unless FATAL warnings are in effect, the minimum needed is use warnings FATAL=>'inplace';; Update: fixed as per choroba's reply, thanks!):
    my $data = do { local (*ARGV,$/); @ARGV=$file; <> };

Minor edits for clarity.

Update 2: Actually, I made a mistake in the last example when I first fixed it, it is now tested and correct.

Replies are listed 'Best First'.
Re^2: Any downsides to this slurp idiom?
by choroba (Cardinal) on Jul 09, 2018 at 16:46 UTC
    Note that localizing @ARGV could be not enough (because eof(ARGV) might remain true). So,
    my $data = do { local ( *ARGV, $/ ); @ARGV = ("$file"); <> };

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1217663]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2023-03-30 13:53 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (74 votes). Check out past polls.