dreeves dreeves - 10 months ago 42
Perl Question

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.


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;
my $text = read_text($filename);

or Path::Tiny:

use Path::Tiny;