Search code examples
perlstringfile-iofile

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


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.


Solution

  • How about this:

    use File::Slurp;
    my $text = read_file($filename);
    

    ETA: note Bug #83126 for File-Slurp: Security hole with encoding(UTF-8). I now recommend using File::Slurper (disclaimer: I wrote it), also because it has better defaults around encodings:

    use File::Slurper 'read_text';
    my $text = read_text($filename);
    

    or Path::Tiny:

    use Path::Tiny;
    path($filename)->slurp_utf8;