What do Perl functions that return Boolean actually return

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

    It probably won't ever change, but perl does not specify the exact boolean value that defined(...) returns.

    When using Boolean values good code should not depend on the actual value used for true and false.

    Example:

    # not so great code:
    my $bool = 0;   #
    ...
    if (some condition) {
      $bool = 1;
    }
    
    if ($bool == 1) { ... }
    
    # better code:
    my $bool;       # default value is undef which is false
    
    $bool = some condition;
    
    if ($bool) { ... }
    

    99.9% of the time there is no reason to care about the value used for the boolean. That said, there are some cases when it is better to use an explicit 0 or 1 instead of the boolean-ness of a value. Example:

    sub foo {
        my $object = shift;
        ...
        my $bool = $object;
        ...
        return $bool;
    }
    

    the intent being that foo() is called with either a reference or undef and should return false if $object is not defined. The problem is that if $object is defined foo() will return the object itself and thus create another reference to the object, and this may interfere with its garbage collection. So here it would be better to use an explicit boolean value here, i.e.:

      my $bool = $object ? 1 : 0;
    

    So be careful about using a reference itself to represent its truthiness (i.e. its defined-ness) because of the potential for creating unwanted references to the reference.

提交回复
热议问题