in reply to Treating the file contents of a text file as a string

local $/ = undef; #slurp entire file my $string; open (my $FH, '<', $file1); $string = <$FH>; close $FH; open (my $FH, '<', $file2); $string .= <$FH>; #notice the concatenation close $FH;
UPDATE: changed the $/ assignment to local.

Stop saying 'script'. Stop saying 'line-noise'.
We have nothing to lose but our metaphors.

Replies are listed 'Best First'.
Re^2: Treating the file contents of a text file as a string
by grinder (Bishop) on May 22, 2008 at 08:00 UTC

    It would be better to minimise the change to the global $/ (record separator) variable, as this may cause action at a distance in some other part of the code (or a module). This is done by reducing the scope to the shortest possible block.

    You are also repeating yourself. This is not good.

    my $string = slurp($file1) . slurp($file2); sub slurp { my $file = shift; open $fh, <, $file or do { warn "Failed to open $file for input: $!\n"; return ''; } local $/ = undef; return <$fh>; # $fh goes out of scope, file closed automatically }

    • another intruder with the mooring in the heart of the Perl

Re^2: Treating the file contents of a text file as a string
by Burak (Chaplain) on May 22, 2008 at 08:03 UTC
    undef $/; #slurp entire file
    That's a very bad idea. You must *NOT* modify special globals like that. Use localised versions and a minimal scope...