Slurp a file into a scalar
So you want a file in a scalar, eh?
Well in Perl, there's a simple idiom for doing so
open(my $fh, "<", "file.txt") or die "$!";
my $contents = do { local $/; <$fh> };
close($fh) or die "$!;
# $contents now contains the contents of file.txt
print $contents;
That's all there is to it. First we unset the input record separator variable ($/
) for the block, and then we just return the contents of the file from the block.
The input record separator variable determines what Perl considers a line. Normally this is set to newline, but since we don't want an array, we just unset it so that perl thinks the entire file is a line.
Since the whole file is now just one line, using the <>
to get the contents will return a scalar.
NOTE: It's important that we do this inside an anonymous block. We don't want to fuck any other Perl modules that make assumptions about $/
.
Written by William Orr
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Perl
Authors
janosgyerik
25.16K
Jean-Remy Duboc
12.25K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#