Reputation: 21625
How to understand the assign of diamond operator (<>
) to empty list in Perl like below, does it make any assignment happen since there is no variable involved?
print (()=<>)
The above prints out nothing but the below prints line count in <>
. How does the line count pass to $x
?
print $x=()=<>
Upvotes: 1
Views: 435
Reputation: 30577
The <>
operator behaves differently depending on the context. In scalar context it gives you the next line read, while in list context it reads until EOF and gives you a list of the lines it has read.
Doing this:
()=<>
does not assign anything, but it does enforce list context, so that <> delivers a list of all lines read.
Doing this:
print $x=()=<>;
results in the assignment operator being interpreted in scalar context, so yielding the number of lines (since a list assignment in scalar context returns the number of elements produced by the expression on the right hand side of the assignment).
This also works:
print (scalar (()=<>));
Another interesting aspect is why this:
print <>;
prints all the lines in the file and yet this:
print (()=<>);
prints nothing. The reason is that the result of a list assignment expression is the a list of the values assigned. In the latter case, no values are assigned, so the result of the expression (which is then consumed by print) is an empty list.
Try this:
print ((undef,undef)=<>);
You will find it gives you the first two lines of the input file. Even though those lines are assigned to 'undef', they are still assigned, so they are still part of the result of the expression.
For a more complete explanation of how =()=
works you might like to read perlsecret as per the comment by ThisSuitIsBlackNot.
Upvotes: 10