← Back to Perl Course | Chapter 5: File I/O | Lesson 3 of 7

Reading files line by line

The diamond operator reads one line at a time, so even huge files use little memory.

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

perl
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
Common Mistakes
  1. Forgetting to chomp and getting doubled newlines
  2. Reading a whole file into an array for a huge file
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.