For example, a hash in scalar context might have returned the total number of keys and values, hence double the number of keys — but it doesn't, as the language designers thought that stats about the internal state of the hash itself were more interesting, especially as there is no other way (barring XS) to get at them. (And no, noone hardly ever uses it, except for debugging and illustrative purposes.)
To illustrate:
Result:%hash = ( a => 1, b => 2, c => 3 ); %hash = ( a => 1, b => 2, c => 3 ); $s = keys %hash; # scalar context: number of keys # vs. my @a = keys %hash; # list context: keys $t = @a; # array in scalar context: number of items printf "\$s is \$t: %s\n\$s: %s\n\$t: %s\n", $s eq $t ? 'yes' : 'no', +$s, $t; printf "\$s is \$t: %s\n", $s eq $t ? 'yes' : 'no';
$s is $t: yes $s: 3 $t: 3
Result:%hash = ( a => 1, b => 2, c => 3 ); $s = %hash; # scalar context: hash stats # vs. my @a = %hash; # list context: key/value pairs $t = @a; # array in scalar context: number of items printf "\$s is \$t: %s\n\$s: %s\n\$t: %s\n", $s eq $t ? 'yes' : 'no', +$s, $t;
$s is $t: no $s: 3/8 $t: 6
Beginning Perl programmers better learn to recognize the fact that functions/keywords may return unrelated results depending on the calling context, scalar vs. list. You may compare the results to other results for learning purposes, like Roger did, but you must recognize the fact that these similarities in behaviour are incidental, and sooner rather than later. When in doubt, you better get into the habit of looking up what a function/keyword returns in scalar/list context, instead of to speculate. Oh, and there's no such thing as a list in scalar context. (Yes, that's a quote. :))
In reply to Re^3: Count values of the inner hash?
by bart
in thread Count values of the inner hash?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |