The reason your second block of code isn't used more is because it is much slower. On small amounts of data, you won't notice, but on larger ones you will. Why?
In the top block of code, perl knows to just read, as fast as reasonable, the entire contents of a file and store it to a variable.
In the lower block of code, it must read one line at a time (which takes longer, partly because there must be a check for line endings). Then, it must join those lines into a string before returning. That's a lot of extra steps.
Actually, your "standard" way of slurping is less than ideal as well, since you are copying the string when your function returns. Why not:
my $content;
{
local $/ = undef;
open my $fh, $_[0] or die "Can't open $_[0]: $!";
$content = <$fh>;
}
Or, if it really must be abstracted into a sub, pass around a reference?
sub slurp {
local $/ = undef;
open my $fh, $_[0] or die "Can't open $_[0]: $!";
my $slurp = <$fh>;
return \$slurp;
}
my $content = slurp('filename');
print $$content;
Of course, you could avoid all this re-inventing of the wheel and just use Slurp:
use Slurp;
my $content = slurp('filename');
|