in reply to Re^2: keys(%hash) not in scalar context in printf
in thread keys(%hash) not in scalar context in printf
The use as an rvalue in a mathematical expression to the right of a scalar (0) forces the interpretation of the list in scalar context, as the lexer parses from left to right.
Note that your "to the right of" can be dropped and that everything after your comma above is irrelevent. keys(%hash) + 0 would work just as well for getting at the number of keys even in a list context.
While you're saving a keystroke or two, you are making absolutely no gains in terms of performance, and potentially losing some if your platform is actually foolish enough to perform the addition to zero.
I almost never use scalar. I frequently use 0+ and sometimes use ''. exactly because they are clearer than scalar. 0+ means that I want to interpret the following thing as a number. Perhaps this is so natural to me since I was using it way back in the day with Turbo Pascal. I use ''. when I want to make it clear that I'm getting at the value as a string. In Perl6, just + will be enough to say "I want the number".
I don't care about saving a few keystrokes nor about performance trivialities. I care about readability and maintainability. 0+ says more than scalar. Sure, pick any part of Perl and you'll likely find some that aren't familiar with it. But even someone who isn't familiar with 0+ can likely figure out that the result is a number. I find that 0+keys... is more likely to be understood as returning "the number of keys" even by someone not deeply familiar with Perl. So I find it much clearer than scalar keys... (more natural to understand while conveying more information).
- tye
|
|---|