readline#
Read one or more records from a filehandle.
readline is the input primitive behind the <FH> diamond operator.
It reads from the filehandle named by EXPR (a typeglob, a glob
reference, or an IO::Handle), using the current value of $/ to
decide where one record ends. If EXPR is omitted, *ARGV is read.
In scalar context it returns the next record; in list context it
returns every remaining record. End-of-file is signalled by undef
(scalar) or an empty list.
Synopsis#
my $line = readline $fh; # one record, scalar context
my @all = readline $fh; # every remaining record
my $line = <$fh>; # same as scalar readline $fh
my @all = <$fh>; # same as list readline $fh
readline; # reads from *ARGV
What you get back#
Scalar context: the next record as a string, or
undefat end-of-file or on error. The record includes its terminator (the current$/) unless the last record in the file is missing one. After the returned value,$.is incremented — see the section on global state below.List context: a list of every remaining record until end-of-file. An empty list means the handle was already at EOF.
Slurp mode on an empty file: when
$/isundefand context is scalar, the first call on a zero-byte handle returns''(empty string, defined); the next call returnsundef. This letsdefined($slurp = readline $fh)distinguish an empty file from a missing one without a separate-stest.
Global state it touches#
$/— input record separator. Controls what counts as “one record”. Default is"\n". Special values are covered under Record modes below. Also known as$INPUT_RECORD_SEPARATORor$RSunderuse English.$.— current input line number of the last handle read.readlineincrements$.once per record returned.$.is reset when the handle is explicitlyclosed, but not when*ARGVrolls from one file to the next — that continues counting across the whole input. Also$INPUT_LINE_NUMBERor$NRunderuse English.$_— the default scalar. When areadlinecall (or its<FH>equivalent) is used as the condition of awhileorforloop, Perl implicitly assigns the result to$_and testsdefined, not truth.while (<$fh>) { ... }is therefore safe on lines containing"0"or"".$!— errno. On a read error,readlinereturnsundef(scalar) or a truncated list, and sets$!to the operating-system error.@ARGV— whenEXPRis omitted (or the handle isARGV), each end-of-file causes Perl toopenthe next filename from@ARGVand continue reading. An empty@ARGVmakesARGVreadSTDIN.
Record modes#
$/ selects one of four reading modes:
Line mode (default) —
$/is a non-empty string. A record ends at the next occurrence of that string. With the default"\n", one call returns one line including its newline.Paragraph mode —
$/ = "". A record ends at the next run of two or more consecutive newlines. Leading blank lines before the first paragraph are skipped; the terminating blank line(s) are included in the returned string. Uselocal $/ = ""to confine the change to a block.Slurp mode —
$/ = undef. The first call returns the entire remaining contents of the handle as one string; the next call returnsundef. On an empty file, see the special case under What you get back.Fixed-record mode —
$/ = \N(a reference to a positive integer) or$/ = \"N". Each call reads exactlyNbytes, or fewer at end-of-file. Useful for binary framing. The result is still counted as one record for$..
Changes to $/ take effect on the next readline call. Scope them
with local so a subroutine does not silently change the caller’s
idea of “line”.
Examples#
Idiomatic line-by-line read. The while condition implicitly
assigns to $_ and tests defined:
open my $fh, "<", "input.txt" or die "open: $!";
while (<$fh>) {
chomp;
print "line $.: $_\n";
}
close $fh;
Explicit readline with error detection. eof must be checked
separately from the return value, because a legitimate line can be
the empty string:
while ( ! eof($fh) ) {
defined( my $line = readline $fh )
or die "readline failed: $!";
# ... process $line ...
}
Slurp a whole file into a scalar:
my $contents = do {
local $/; # undef — slurp mode
open my $fh, "<", $path or die "open $path: $!";
readline $fh;
};
Paragraph mode — read an RFC-822-style message header block:
open my $fh, "<", "message.eml" or die $!;
local $/ = "";
my $headers = <$fh>; # up to the first blank line
my $body = do { local $/; <$fh> };
Fixed-record mode — read 512-byte blocks from a device file:
open my $fh, "<:raw", "/dev/sda" or die $!;
local $/ = \512;
while (defined(my $block = <$fh>)) {
last if length($block) < 512; # short read at EOF
# ... process $block ...
}
List context — pull every remaining line at once. Cheap for small files, ruinous for large ones:
open my $fh, "<", "hosts" or die $!;
my @lines = <$fh>; # every line, including terminators
chomp @lines;
Reading from *ARGV with no explicit handle — the classic Perl
filter idiom. @ARGV is consumed as a list of filenames, or
STDIN is read if @ARGV is empty:
while (defined(my $line = readline)) {
print $line; # cat(1) in one line
}
Edge cases#
EOF vs. error: scalar
readlinereturnsundeffor both. Calleof($fh)or check$!to distinguish them. Insidewhile (<$fh>)the loop exits on either; add an explicitdefinedplus$!check when you need to tell them apart.A file with no trailing newline: the last record is returned without a terminator in line mode.
chompis a no-op on such a value, which is the correct behaviour.Paragraph mode on a file of only blank lines: returns
undefimmediately — there is no non-empty paragraph to yield.Slurp mode, empty file: first call returns
''(defined, zero-length); the second returnsundef. Do not branch on truthiness of the first read.Fixed-record mode with a short read at EOF: returns the remaining bytes (possibly fewer than
N), thenundefon the next call. Checklengthif you need exactlyN.The
ARGVmagic handle: when reading from*ARGV,eof()with no argument returns true only at the very end of all@ARGVfiles, whileeof(ARGV)is true at the end of each file. You cannot use thedefined(readline) or die "...: $!"idiom against*ARGVto distinguish EOF from error — open each filename yourself if you need that.Already-closed handle:
readlinereturnsundefand sets$!to"Bad file descriptor". Underuse warningsareadline() on closed filehandlewarning is emitted.Encoding layers:
readlinereturns whatever the handle’s PerlIO stack produces. A:utf8or:encoding(...)layer decodes bytes into characters; a:rawhandle returns bytes. Mixing a multi-byte$/with a byte handle can split characters.Mid-record
$/change: only the nextreadlinecall observes the new separator. Any already-buffered data is re-scanned against it.<FH>vs.<$fh>vs.<>: these are allreadlineunder the hood.<FH>reads from the typeglobFH;<$fh>reads from the handle in$fh;<>(or<<>>for safer filename handling) reads from*ARGV. The<pattern>form with any other content isglob, notreadline— a different function entirely.Loop condition assignment:
while (my $line = <$fh>) { ... }testsdefined, not truth, only because the parser rewrites it.while (($line = <$fh>)) { ... }with the extra parentheses does not get the rewrite, and will loop forever on input containing"0\n".
Differences from upstream#
Fully compatible with upstream Perl 5.42.
See also#
open— obtain the filehandle thatreadlineconsumesread— fixed-length byte read that ignores$/; use when you want a byte count, not a recordeof— test whether the nextreadlinewould returnundef; behaves specially for*ARGV$/— input record separator; controls line, paragraph, slurp, and fixed-record modes$.— current input line number, incremented by every successfulreadline