What do Perl functions that return Boolean actually return

后端 未结 4 912
名媛妹妹
名媛妹妹 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:30

    Since that's the official man page I'd say that its exact return value is not specified. If the Perl documentation talks about a Boolean value then then it almost always talks about evaluating said value in a Boolean context: if (defined ...) or print while <> etc. In such contexts several values evaluate to a false: 0, undef, "" (empty strings), even strings equalling "0".

    All other values evaluate to true in a Boolean context, including the infamous example "0 but true".

    As the documentation is that vague I would not ever rely on defined() returning any specific value for the undefined case. However, you'll always be OK if you simply use defined() in a Boolean context without comparing it to a specific value.

    OK: print "yes\n" if defined($var)

    Not portable/future proof: print "yes\n" if defined($var) eq '' or something similar

提交回复
热议问题