Reading files line by line
The diamond operator reads one line at a time, so even huge files use little memory.
In this page:
Reading files line by line
In scalar context <$fh> returns the next line, including its newline, and returns undef at the end of the file. A while loop such as while (my $line = <$fh>) reads every line, and Perl adds an implicit defined test so a line containing just "0" does not stop the loop. The special variable $. holds the current line number, and chomp removes the trailing newline.
Note:
Reading with a while loop keeps memory low, so prefer it for large files.
Example: Reading files line by line
use strict;
use warnings;
my $file = "demo_lines.txt";
open(my $w, '>', $file) or die "Cannot write: $!";
print $w "alpha\nbeta\n\ngamma\n";
close $w;
open(my $fh, '<', $file) or die "Cannot read: $!";
while (my $line = <$fh>) {
chomp $line;
next if $line eq '';
print "$.: $line\n";
}
close $fh;
unlink $file;
# Output:
# 1: alpha
# 2: beta
# 4: gamma
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting to chomp and getting doubled newlines
- Reading a whole file into an array for a huge file
- Forgetting that the last line may lack a newline
Chapter Summary
- <$fh> in a while loop reads line by line
- chomp removes the newline
- $. holds the line number
- The loop ends at end of file
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: