in reply to keys(%hash) not in scalar context in printf

Hi jeanluca,

My own preference in this case is almost always:

printf "keys=%d\n", 0+(keys %r);

I just like the brevity of that over scalar.


s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/

Replies are listed 'Best First'.
Re^2: keys(%hash) not in scalar context in printf
by Obidan (Initiate) on Apr 18, 2007 at 18:04 UTC
    Hello, all.

    With respect to the above code, it should be known that this will be interpreted in the exact same fashion as the scalar call, possibly with added instructions.

    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.

    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.

    Furthermore, as a powerful perl monk, one must remember to *occasionally* pay heed to the twin divinities of readability and maintainability, lest they smite thee and thy code with hours of frustrating bug-hunts.

    The "scalar" solution is by far the most straight-forward and accepted way to handle this.

    Obidan

      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