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 => [EMAIL PROTECTED] => www.petdance.com => AIM:petdance




_______________________________________________
Houston mailing list
[email protected]
http://mail.pm.org/mailman/listinfo/houston
Website: http://houston.pm.org/

Reply via email to