Search⌘ K
AI Features

Reading and Writing to Files

Explore techniques for reading and writing files in Perl, including safe line-by-line reading, handling binary data, and properly closing filehandles. Understand idiomatic Perl for file operations to write clean and efficient code.

Reading from files

Given a filehandle opened for input, read from it with the readline built-in, also written as <>.

A while idiom

A common idiom reads a line at a time in a while() loop:

Perl
open my $fh, '<', 'some_file';
while (<$fh>) {
chomp;
say "Read a line '$_'";
}

In scalar context, readline reads a single line of the file and returns it or returns undef if it has reached the end of file (test that condition with the eof built-in).

Each iteration in this example returns the next line or undef. This while idiom explicitly checks ...