Skrevet av Emne: Perl: How to "slurp" a file  (Lest 4290 ganger)

ATC

  • Gjest
Perl: How to "slurp" a file
« på: 27. ſeptember 2008, 18:24 pm »
  • [applaud]0
  • [smite]0
  • When reading from a file handle into a scalar, data is only fetched one line at a time. To read the whole file I have to use an array and then join() it together. Isn't there an easier way?



    ATC

    • Gjest
    [Solved] Perl: How to "slurp" a file
    « Svar #1 på: 27. ſeptember 2008, 18:24 pm »
  • [applaud]0
  • [smite]0
  • Ofcourse there is :-)

    Perl uses the built-in variable $/ for the line terminator to determine what a line is. To 'slurp' an entire file into a scalar, simply undef $/ like so:

    my $temp = $/; # Keep for later
    undef $/;
    my $var = <$fh>;
    $/ = $temp; # Restore default behaviour