Consider the following program:

perl -MDevel::Peek -le 'my @nonempty = (1); my @empty = (); print Dump +(scalar @nonempty); print Dump(scalar @empty)' SV = IV(0x563dfe2d16f0) at 0x563dfe2d1700 REFCNT = 1 FLAGS = (TEMP,IOK,pIOK) IV = 1 SV = PVNV(0x563dfe2d0200) at 0x563dfe2ce410 REFCNT = 2147483647 FLAGS = (PADTMP,IOK,NOK,POK,READONLY,PROTECT,pIOK,pNOK,pPOK) IV = 0 NV = 0 PV = 0x7fb0f957d3c2 "0" CUR = 1 LEN = 0

Which is to say, scalar returns a PV if the array is empty, and an IV if it is not. This can be a problem, because most serializers, including JSON modules, will encode the PV as "0" and the IV as 1, which will cause a problem if the consumer of the resulting JSON expects strict type conformance.

Is there a logical reason for this discrepancy?

(Yes, I know that I could just do 0+scalar @array - my point is that that shouldn't be necessary.)


In reply to Reason for this discrepancy with scalar? by kikuchiyo

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.