Reading a whole file
In list context <$fh> returns every line, and setting a special variable can read the file in one piece.
In this page:
Reading a whole file
In list context the readline operator returns all remaining lines as a list, which is handy for small files. To get the whole file as a single string, set the input record separator $/ to undef inside a local block, which is called slurping. chomp with a list removes the newline from every element.
Note:
Use local $/; inside a small block so the change does not affect the rest of the program.
Example: Reading a whole file
use strict;
use warnings;
my $file = "demo_slurp.txt";
open(my $w, '>', $file) or die "Cannot write: $!";
print $w "one\ntwo\nthree\n";
close $w;
open(my $fh, '<', $file) or die "Cannot read: $!";
my @lines = <$fh>;
close $fh;
chomp @lines;
print "lines: ", scalar(@lines), " -> @lines\n";
my $content = do {
local $/;
open(my $in, '<', $file) or die "Cannot read: $!";
<$in>;
};
print "characters: ", length($content), "\n";
my $newlines = () = $content =~ /\n/g;
print "newlines: $newlines\n";
unlink $file;
# Output:
# lines: 3 -> one two three
# characters: 14
# newlines: 3
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Slurping very large files into memory
- Setting $/ to undef and forgetting to restore it
- Forgetting that each element read in list context still ends with a newline
Chapter Summary
- List context returns all lines
- local $/ = undef slurps a file
- chomp works on a whole array
- Only slurp small files
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: