')

Read an entire file into a string

There are several ways in Perl to read an entire file into a string. Some ways are better than others. Below are some examples of 'better practice'.

If you have access to CPAN, you can use the File::Slurp module:

use 5.10.1;
use File::Slurp;

my $text_file = read_file('text_document.txt');

The code above uses File::Slurp's read_file function to read the entire contents of a file with the file name "text_document.txt" as a string into $text_file. Using File::Slurp is recommended as it will simplify your code and 'just work'. If for some reason you want to write your own solution sans module, try this:

use 5.10.1;

open my $fh, '<', 'text_document.txt' or die "Can't open file $!";
my $text_file = do { local $/; <$fh> };

What this code does is open a filehandle to the target file, using the three-argument version of open. Then within the do { } block it localises Perl's record separator variable $/ to undef, so that the diamond <> operator will read all the lines of the file at once (usually $/ is set to newline).


David is the founder and editor of PerlTricks.com. A regular attendee of NY.pm, he works as a technology consultant in New York City.