For large files, consider File::Slurp. It’s faster than the conventional approaches:
# Slurp the whole file
{
local $/ = undef;
open my $fh, '<', 'myfile' or die "Couldn't open file: $!";
binmode $fh;
my $string = <$fh>;
close $fh;
}
Without binmode:
{
local $/ = undef;
open my $fh, '<', 'myfile' or die "Couldn't open file: $!";
my $string = <$fh>;
close $fh;
}
Join the lines:
open my $fh, '<', 'myfile' or die "Couldn't open file: $!";
my $string = join('', <$fh>);
close $fh;
Append in a loop:
open my $fh, '<', 'myfile' or die "Couldn't open file: $!";
my $string;
while (<$fh>) {
$string .= $_;
}
close $fh;
Read a fixed number of bytes:
open my $fh, '<', 'sample.txt' or die "Error: $!\n";
read($fh, my $data, 2000);
close $fh;
The read function takes a filehandle, a destination variable, and the number of bytes to read. The example above reads 2000 bytes into $data.
Using sysread:
my $file = 'sample.txt';
{
local *FH;
open FH, '<', $file or die $!;
sysread FH, my $content, -s $file;
close FH;
}