Perl Scripts ·

Perl: Reading a File with while vs foreach

By Manu Mathew, Technical Lead Engineer · Published 28 January 2016 · Last updated 5 October 2026

Isometric illustration comparing a file read line by line on a blue belt with a whole file dumped at once

Reading a file in Perl usually means a loop, and Perl offers two that look almost the same. They behave quite differently on large files.

Quick answer

while (my $line = <$fh>) reads one line at a time. foreach my $line (<$fh>) reads the whole file into a list before the loop starts. For small files you won’t notice; for large files, or when you want to stop early, use while.

What does while do?

Each pass reads the next line, so memory use stays small and you can stop as soon as you have what you need. (chomp removes the newline; see removing newlines with chomp().)

use strict;
use warnings;

my $path = 'notes.txt';    # contains: alpha, beta, STOP, gamma
open my $fh, '<', $path or die "Cannot open $path: $!";
while (my $line = <$fh>) {
    chomp $line;
    print "$.: $line\n";
    last if $line eq 'STOP';    # the rest of the file is never read
}
close $fh;
1: alpha
2: beta
3: STOP

What does foreach do differently?

<$fh> in list context reads every line first. One visible side effect: the line counter $. already holds the last line number on every pass.

open my $fh, '<', $path or die "Cannot open $path: $!";
foreach my $line (<$fh>) {    # all lines are read before the first pass
    chomp $line;
    print "$.: $line\n";
}
close $fh;
4: alpha
4: beta
4: STOP
4: gamma

When is foreach fine?

When the file is small and you need all the lines anyway, for example to sort them. Even then, reading into an array first (my @lines = <$fh>;) makes the intent clearer.

Frequently asked questions

Does while cope with files that have very long lines?

Yes, but each line is read whole, so one huge line still uses that much memory. For files without useful line breaks, such as binary data or one-line JSON, read fixed-size blocks with read instead.

What does $. hold after the loop?

The number of the last line read from the most recent filehandle. It resets when you close that handle, so read it before close if you need the line count, or keep your own counter.

How do I read a whole file into one string?

Turn off line splitting while you read: my $text = do { local $/; <$fh> };. This reads the file in one go, which is fine for small files such as templates or configuration, but not for large logs.

How do I read a UTF-8 file correctly?

Open it with an encoding layer: open my $fh, '<:encoding(UTF-8)', $path. Perl then decodes each line into characters, so length, substr and regular expressions work on letters rather than bytes. Write output with a matching layer.

Related notes: removing newlines with chomp(); breaking out of loops in Perl; Perl files, folders, CSV and downloads; hiring a remote Perl developer.

Need help with Perl code?

If you have Perl code that needs fixing, extending or upgrading, I’m happy to take a look. I work remotely from Kozhikode, Kerala, with teams across India and elsewhere; Perl development and maintenance explains how I help. If you are deciding how to bring someone in, Hiring a remote Perl developer is a short checklist.

You can reach me through the contact section or email me at manu@manu.co.in. A few lines about the system and what you need is a good start.

An earlier version of this note reproduced a Stack Overflow answer (answer 585371, CC BY-SA). This version is rewritten in my own words, with new examples.

Sources: perlop: I/O Operators; perlvar: $.; Stack Overflow question 585341.

Back to the blog