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

mob picture mob · Oct 3, 2009 · Viewed 32.9k times · Source

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 or3 {
    my ($a,$b) = @_;
    return $a or $b;
}

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

I came to Perl 5 from C and Perl 4 and always used || until I saw more scripts using or and I liked the way it looked. But as the above quiz shows, it's not without its pitfalls for the unwary. For people who use both constructs or who use a lot of or, what rules of thumb do you use to decide which construct to use and make sure the code is doing what you think it is doing?

Answer

Igor ostrovsky picture Igor ostrovsky · Oct 3, 2009

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