What is the best way to slurp a file into a string in Perl?

Viewed 29804

Yes, There's More Than One Way To Do It but there must be a canonical or most efficient or most concise way. I'll add answers I know of and see what percolates to the top.

To be clear, the question is how best to read the contents of a file into a string. One solution per answer.

16 Answers

I like doing this with a do block in which I localize @ARGV so I can use the diamond operator to do the file magic for me.

 my $contents = do { local(@ARGV, $/) = $file; <> };

If you need this to be a bit more robust, you can easily turn this into a subroutine.

If you need something really robust that handles all sorts of special cases, use File::Slurp. Even if you aren't going to use it, take a look at the source to see all the wacky situations it has to handle. File::Slurp has a big security problem that doesn't look to have a solution. Part of this is its failure to properly handle encodings. Even my quick answer has that problem. If you need to handle the encoding (maybe because you don't make everything UTF-8 by default), this expands to:

my $contents = do {
    open my $fh, '<:encoding(UTF-8)', $file or die '...';
    local $/;
    <$fh>;
    };

If you don't need to change the file, you might be able to use File::Map.

In writing File::Slurp (which is the best way), Uri Guttman did a lot of research in the many ways of slurping and which is most efficient. He wrote down his findings here and incorporated them info File::Slurp.

open(my $f, '<', $filename) or die "OPENING $filename: $!\n";
$string = do { local($/); <$f> };
close($f);

Things to think about (especially when compared with other solutions):

  1. Lexical filehandles
  2. Reduce scope
  3. Reduce magic

So I get:

my $contents = do {
  local $/;
  open my $fh, $filename or die "Can't open $filename: $!";
  <$fh>
};

I'm not a big fan of magic <> except when actually using magic <>. Instead of faking it out, why not just use the open call directly? It's not much more work, and is explicit. (True magic <>, especially when handling "-", is far more work to perfectly emulate, but we aren't using it here anyway.)

mmap (Memory mapping) of strings may be useful when you:

  • Have very large strings, that you don't want to load into memory
  • Want a blindly fast initialisation (you get gradual I/O on access)
  • Have random or lazy access to the string.
  • May want to update the string, but are only extending it or replacing characters:
#!/usr/bin/perl
use warnings; use strict;

use IO::File;
use Sys::Mmap;

sub sip {

    my $file_name = shift;
    my $fh;

    open ($fh, '+<', $file_name)
        or die "Unable to open $file_name: $!";

    my $str;

    mmap($str, 0, PROT_READ|PROT_WRITE, MAP_SHARED, $fh)
      or die "mmap failed: $!";

    return $str;
}

my $str = sip('/tmp/words');

print substr($str, 100,20);

Update: May 2012

The following should be pretty well equivalent, after replacing Sys::Mmap with File::Map

#!/usr/bin/perl
use warnings; use strict;

use File::Map qw{map_file};

map_file(my $str => '/tmp/words', '+<');

print substr($str, 100, 20);
use Path::Class;
file('/some/path')->slurp;
{
  open F, $filename or die "Can't read $filename: $!";
  local $/;  # enable slurp mode, locally.
  $file = <F>;
  close F;
}

This is neither fast, nor platform independent, and really evil, but it's short (and I've seen this in Larry Wall's code ;-):

 my $contents = `cat $file`;

Kids, don't do that at home ;-).

See the summary of Perl6::Slurp which is incredibly flexible and generally does the right thing with very little effort.

Nobody said anything about read or sysread, so here is a simple and fast way:

my $string;
{
    open my $fh, '<', $file or die "Can't open $file: $!";
    read $fh, $string, -s $file;   # or sysread
    close $fh;
}

Candidate for the worst way to do it! (See comment.)

open(F, $filename) or die "OPENING $filename: $!\n";
@lines = <F>;
close(F);
$string = join('', @lines);
Related