[pm-h] reading a file as a string

Andy Lester andy at petdance.com
Sat May 19 19:31:14 PDT 2007


On May 19, 2007, at 9:25 PM, Russell L. Harris wrote:

> Is there a preferred approach for copying an entire file into a string
> variable, while preserving the record delimiters (the newline
> character)?
>
> I have found two examples; is either of them a good approach?
>
>     open (FILE,$filename) || die "Cannot open '$filename': $!";
>     undef $/;
>     my $file_as_string = <FILE>;
>
>
>     open (FILE,$filename) || die "Cannot open '$filename': $!";
>     my $file_as_string = join '', <FILE>;

Of those two, choose the former.  The second one reads all the lines  
into an array, and the glomps together a big string.  The first one  
just reads into a string.

Do it this way:

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

This lets you localize the $/ so that it gets set back outside the  
scope of the block.  Otherwise, you might try to read from a file  
somewhere else and not know that you changed $/.

Here's another way:

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

xoxo,
Andy

--
Andy Lester => andy at petdance.com => www.petdance.com => AIM:petdance






More information about the Houston mailing list