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 |
In Section
Seekers of Perl Wisdom