With $length = (4,5,6) the thing that gets evaluated in scalar context is (4,5,6), which a list, and so indeed, $length here will be assigned the value '6'. But if you apply scalar context to something else, the result is not always the last element. For exemple in $length = @array the right side is an array, not a list (the two notions are close but not identical in perl, you can see an array as a list encapsulated in an object that changes its behavior), and you get the length. And, another case, reverse in list context will return a list of elements, but in scalar context does not just return the last elements, but the concatenated reverse string.
The reason that the while(($key, $val) = each %hash) works is because the expression that gets evaluated in scalar context is not a list, but an assignment (it's not just data, it's an action), and list assignments, unlike simple lists eval to the size of the list. You can see ($key, $val) = each %hash as a simpler way to write AssignTo(key => \$key, val => $val, from => \%hash) (this does not work), where AssignTo is a fonction that returns the number of elements 'removed' from the hash. If indeed, the while tested the last value, and not the number of elements, a hash like (1 => 0, 2 => 0) would fail to be read by the loop, because $val would be 0, which is false.
The difference between just a list and a list assignment is used in this kind of code: my $numberOfMatches = () = /regex/g; Where the right part is evaluated first (so the matches of the regex are copied to (), ie thrown away), and then my $numberOfMatches = LIST_ASSIGNMENT is evaluated, where the value of LIST_ASSIGNMENT is the number of elements that where redirected towards ().
Edit: I feel like I wrote too much an wasn't really clear I hope I didn't confuse you even more ...
In reply to Re: each %hash: scalar context of list (undef, undef) is false
by Eily
in thread each %hash: scalar context of list (undef, undef) is false
by rsFalse
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |