file-io intermediate

How to slurp an entire file into a variable in Perl

Question

What is the best way to read an entire file into a single variable in Perl?

The modern way uses the Path::Tiny module, but you can also use core Perl features:

use strict;
use warnings;

# Method 1: Using File::Slurp (CPAN module)
# use File::Slurp;
# my $content = read_file('data.txt');

# Method 2: Core Perl with local $/
open my $fh, '<', 'data.txt' or die "Cannot open: $!";
my $content = do { local $/; <$fh> };
close $fh;

print "File size: ", length($content), " bytes\n";

# Method 3: Path::Tiny (recommended)
# use Path::Tiny;
# my $content = path('data.txt')->slurp_utf8;

# One-liner to slurp
# perl -0777 -ne 'print length' file.txt

Setting $/ to undef makes the diamond operator read the entire file at once. For production code, use Path::Tiny from CPAN.

Was this helpful?

Related Questions