Last Updated: February 25, 2016
· worr

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 $/.