Perl初始化值:“”vs q {}和0 vs(1 == 2)

时间:2014-04-29 19:01:23

标签: perl

my $EMPTY = q{};
use constant TRUE  => ( 1==1 );
use constant FALSE => ( 1==2 );


my $a = "";   vs my $a = $EMPTY;             
my $b = 0;    vs my $b = FALSE

对于什么应该使用哪个有什么区别?
这取决于某些情况吗?
如果是这样,那么您希望何时使用my $b = 0;超过my $b = FALSE,反之亦然的情况是什么?

2 个答案:

答案 0 :(得分:8)

  • ""q{}都生成零长度字符串。

    >perl -MDevel::Peek -e"$_ = q{}; Dump($_);"
    SV = PV(0x306748) at 0x4c9058
      REFCNT = 1
      FLAGS = (POK,pPOK)            <--- Contains a string.
      PV = 0x4ac9e8 ""\0
      CUR = 0                       <--- Length of the string is zero.
      LEN = 16
    
  • 0生成数字零。

    >perl -MDevel::Peek -e"$_ = 0; Dump($_)"
    SV = IV(0x229088) at 0x229098
      REFCNT = 1
      FLAGS = (IOK,pIOK)            <--- Contains a signed integer.
      IV = 0                        <--- Contained integer is zero.
    
  • (1==2)生成一个包含空字符串且数值为零的标量。

    >perl -MDevel::Peek -e"$_ = 1==2; Dump($_);"
    SV = PVNV(0x1fc598) at 0x259038
      REFCNT = 1
      FLAGS = (IOK,NOK,POK,pIOK,pNOK,pPOK)   <--- A signed int, a float and a str.
      IV = 0                        <--- Contained integer is zero.
      NV = 0                        <--- Contained floating point number is zero.
      PV = 0x23ca18 ""\0
      CUR = 0                       <--- Length of the string is zero.
      LEN = 16
    

答案 1 :(得分:4)

您创建的FALSE值是Perl中特殊PL_sv_no变量的副本。此值在数字上为零且为空状态时是唯一的,并且使用==eq运算符进行比较时不会发出警告。相比之下,由""q{}创建的普通空字符串将生成==

的警告