Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 555
Qiang Li Avatar asked Feb 21 '12 20:02

Qiang Li


People also ask

What is the purpose of diamond operator in Perl?

The Diamond operator is almost exclusively used in a while-loop. It allows us to iterate over the rows in all the files given on the command line. it will print the content of all 3 files line-by-line.

What does-> mean in Perl?

The arrow operator ( -> ) is an infix operator that dereferences a variable or a method from an object or a class. The operator has associativity that runs from left to right.


2 Answers

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

like image 138
Eric Strom Avatar answered Nov 11 '22 03:11

Eric Strom


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.

like image 40
mob Avatar answered Nov 11 '22 04:11

mob