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
- How to use File::Find to recursively search directories in Perl?
- How to use Path::Tiny for file operations in Perl?
- How to use File::Copy to copy files in Perl?
- How to get file modification time in Perl?
- How to use File::Slurp to read files in Perl?
- How to open a file with specific encoding in Perl?