What is the difference between Perl's ( or, and ) and ( ||, && ) short-circuit operators?

前端 未结 5 1393
暖寄归人
暖寄归人 2020-11-29 06:44

Which of these subroutines is not like the other?

sub or1 {
    my ($a,$b) = @_;
    return $a || $b;
}

sub or2 {
    my ($a,$b) = @_;
    $a || $b;
}

sub          


        
5条回答
  •  既然无缘
    2020-11-29 06:50

    Due to the low precedence of the 'or' operator, or3 parses as follows:

    sub or3 {
        my ($a,$b) = @_;
        (return $a) or $b;
    }
    

    The usual advice is to only use the 'or' operator for control flow:

    @info = stat($file) or die;
    

    For more discussion, see the perl manual: http://perldoc.perl.org/perlop.html#Logical-or-and-Exclusive-Or

提交回复
热议问题