Search code examples
perllogical-operatorsshort-circuiting

How does the `||` work in Perl?


How does the || works in Perl? I want to achieve c style || operation.

@ARRAY=qw(one two THREE four);

$i=0;

if(($ARRAY[2] ne "three")||($ARRAY[2] ne "THREE"))         #What's the problem with this
{
   print ":::::$ARRAY[2]::::::\n";
}


while(($ARRAY[$i] ne "three")||($ARRAY[$i] ne "THREE"))       #This goes to infinite loop

{

 print "->$ARRAY[$i]\n";
   $i=$i+1;

}

Solution

  • It works exactly the way you thought it would. However, you have a thinko in your condition. Every value is either not one value or not another value.

    I believe you might have wanted

    if ($ARRAY[2] ne 'three' && $ARRAY[2] ne 'THREE') { ...
    

    or

    if ($ARRAY[2] eq 'three' || $ARRAY[2] eq 'THREE') { ...
    

    You might also want some case-insensitive way of comparing, like

    if (lc $ARRAY[2] ne 'three') { ...
    

    or possibly a case-insensitive regexp match.