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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With