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        


In reply to Re^3: keys(%hash) not in scalar context in printf (clarity) by tye
in thread keys(%hash) not in scalar context in printf by jeanluca

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.