What do Perl functions that return Boolean actually return

后端 未结 4 914
名媛妹妹
名媛妹妹 2020-12-06 11:02

The Perl defined function (and many others) returns \"a Boolean value\".

Given Perl doesn\'t actually have a Boolean type (and uses values like 1 for t

4条回答
  •  粉色の甜心
    2020-12-06 11:22

    In almost all cases (i.e. unless there's a reason to do otherwise), Perl returns one of two statically allocated scalars: &PL_sv_yes (for true) and &PL_sv_no (for false). This is them in detail:

    >perl -MDevel::Peek -e"Dump 1==1"
    SV = PVNV(0x749be4) at 0x3180b8
      REFCNT = 2147483644
      FLAGS = (PADTMP,IOK,NOK,POK,READONLY,pIOK,pNOK,pPOK)
      IV = 1
      NV = 1
      PV = 0x742dfc "1"\0
      CUR = 1
      LEN = 12
    
    >perl -MDevel::Peek -e"Dump 1==0"
    SV = PVNV(0x7e9bcc) at 0x4980a8
      REFCNT = 2147483647
      FLAGS = (PADTMP,IOK,NOK,POK,READONLY,pIOK,pNOK,pPOK)
      IV = 0
      NV = 0
      PV = 0x7e3f0c ""\0
      CUR = 0
      LEN = 12
    

    yes is a triple var (IOK, NOK and POK). It contains a signed integer (IV) equal to 1, a floating point number (NV) equal to 1, and a string (PV) equal to 1.

    no is also a triple var (IOK, NOK and POK). It contains a signed integer (IV) equal to 0, a floating point number (NV) equal to 0, and an empty string (PV). This means it stringifies to the empty string, and it numifies to 0. It is neither equivalent to an empty string

    >perl -wE"say 0+(1==0);"
    0
    
    >perl -wE"say 0+'';"
    Argument "" isn't numeric in addition (+) at -e line 1.
    0
    

    nor to 0

    >perl -wE"say ''.(1==0);"
    
    
    >perl -wE"say ''.0;"
    0
    

    There's no guarantee that this will always remain the case. And there's no reason to rely on this. If you need specific values, you can use something like

    my $formatted = $result ? '1' : '0';
    

提交回复
热议问题