Reading and Writing to Files

Learn how to read and write to files in Perl.

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:

Press + to interact
main.pl
some_file
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 ...

Access this course and 1400+ top-rated courses and projects.