Read file into variable in Perl

itzy picture itzy · Nov 3, 2010 · Viewed 51.6k times · Source

Possible Duplicate:
What is the best way to slurp a file into a string in Perl?

Is this code a good way to read the contents of a file into a variable in Perl? It works, but I'm curious if there is a better practice I should be using.

open INPUT, "input.txt";
undef $/;
$content = <INPUT>;
close INPUT;
$/ = "\n";

Answer

n0rd picture n0rd · Nov 3, 2010

I think common practice is something like this:

    my $content;
    open(my $fh, '<', $filename) or die "cannot open file $filename";
    {
        local $/;
        $content = <$fh>;
    }
    close($fh);

Using 3 argument open is safer. Using file handle as variable is how it should be used in modern Perl and using local $/ restores initial value of $/ on block end, instead of your hardcoded \n.