Line Input (Angle) Operator
The most heavily used input operator is the line input operator, also
known as the angle operator or the readline function (since that’s what it
calls internally). Evaluating a filehandle in angle brackets
(STDIN, for example) yields the
next line from the associated filehandle. (The newline is included,
so according to Perl’s criteria for truth, a freshly read line is
always true, up until end-of-file, at which point an undefined value
is returned, which is conveniently false.) Ordinarily, you would
assign the input value to a variable, but there is one situation
where an automatic assignment happens. If and only if the line input
operator is the only thing inside the conditional of a while loop, the value is automatically
assigned to the special variable $_. The
assigned value is then tested to see whether it is defined. (This
may seem like an odd thing to you, but you’ll use the construct
frequently, so it’s worth learning.) Anyway, the following lines are
equivalent:
while (defined($_ = <STDIN>)) { print $_ } # the longest way
while ($_ = <STDIN>) { print } # explicitly to $_
while (<STDIN>) { print } # the short way
for (;<STDIN>;) { print } # while loop in disguise
print $_ while defined($_ = <STDIN>); # long statement modifier
print while $_ = <STDIN>; # explicitly to $_
print while <STDIN>; # short statement modifierRemember that this special magic requires a while loop. If you use the input operator anywhere else, you must assign the result explicitly ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access