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
- How to use File::Find to recursively search directories in Perl?
- How to use Path::Tiny for file operations in Perl?
- How to use File::Copy to copy files in Perl?
- How to get file modification time in Perl?
- How to use File::Slurp to read files in Perl?
- How to open a file with specific encoding in Perl?