Ano-Tech Computers
Enter keyword:

Perl: How to "slurp" a file
Problem:
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?
 
Solution:
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


 
Discuss this solution
Did this article solve your problem? Yes No Did not apply

We welcome anyone who is willing to contribute to this public knowledge base, contact siteadmin@atc.no if you have information you would like to share. The idea is not to replace the commercial support sites, but to publish those hard-to-find solutions you've found yourself looking for over and over again.

Show all articles