file-io beginner

How to read a file line by line in Perl

Question

What is the best way to read a text file line by line in Perl?

The most common and efficient way is to use a while loop with the diamond operator:

use strict;
use warnings;

open my $fh, '<', 'data.txt' or die "Cannot open file: $!";

while (my $line = <$fh>) {
    chomp $line;  # Remove newline
    print "Line: $line\n";
}

close $fh;

# For one-liner processing:
# perl -ne 'print if /pattern/' file.txt

Always use lexical filehandles (my $fh) and the three-argument form of open. The chomp function removes the trailing newline character.

Was this helpful?

Related Questions