Qiang Li
Qiang Li

Reputation: 10855

difference between while loop vs. single use of diamond operator in perl

I am confused at the following:

<>; print;

vs.

while(<>){print;}

The first one does not print anything, but second one does. Doesn't <> always store the input read into $_?

Thank you.

Upvotes: 5

Views: 1197

Answers (3)

LanceH
LanceH

Reputation: 1756

From http://perldoc.perl.org/perlvar.html (Talking about $_) :

"The default place to put an input record when a operation's result is tested by itself as the sole criterion of a while test. Outside a while test, this will not happen."

Upvotes: 2

Eric Strom
Eric Strom

Reputation: 40152

The diamond file input iterator is only magical when it is in the conditional of a while loop:

$ perl -MO=Deparse -e '<>; print;'
<ARGV>;
print $_;
-e syntax OK

$ perl -MO=Deparse -e 'while (<>) {print;}'
while (defined($_ = <ARGV>)) {
    print $_;
}
-e syntax OK

This is all documented in perlop

Upvotes: 13

mob
mob

Reputation: 118605

It does not except as the condition of a while statement.

$ perl -MO=Deparse -e 'while(<>) { print }'
while (defined($_ = <ARGV>)) {
    print $_;
}
-e syntax OK

$ perl -MO=Deparse -e '<>; print'
<ARGV>;
print $_;
-e syntax OK

perlop documents that the auto-assignment to $_ only happens in this context:

Ordinarily you must assign the returned value to a variable, but there is one situation where an automatic assignment happens. If and only if the input symbol is the only thing inside the conditional of a "while" statement (even if disguised as a "for(;;)" loop), the value is automatically assigned to the global variable $_ , destroying whatever was there previously. (This may seem like an odd thing to you, but you'll use the construct in almost every Perl script you write.) The $_ variable is not implicitly localized. You'll have to put a "local $_ ;" before the loop if you want that to happen.

Upvotes: 8

Related Questions