They are identical in functionality. Where they differ is precedence. || and && have a higher precedence than and and or. Observe:

use warnings; use strict; my $one = 1; $one += 0 || warn "||\n"; $one += 0 or warn "or\n"; $one += 0 && warn "&&\n"; $one += 0 and warn "and\n";

Output:

|| and

All examples attempt the same thing. Add $one to zero, which should obviously result in true (1). However, in the || example, instead of $one being added to zero, the || has a higher precedence than +=, meaning that the || binds to the zero before the addition-assignment happens, so the left hand side is false, therefore, the warn is executed. In the or line, the += has a higher precedence, meaning the left hand side is evaluated to true, so the warn is ignored.

It's similar for the && and and. && binds to the zero before the +=, so the left side is always going to be false, so the right side (warn) is never evaluated. With and, the addition happens first, then the and evaluation and because the LHS is true, the warn is executed.

Clear as mud? Good. Whenever you're using and or && || and you get results you don't expect, it's almost always related to precedence, especially in long convoluted evaluations where you're using negations and stuff.

Parens allow you to create your own precedence:

($one += 0) || warn "||\n";

There, whatever is in parens will be evaluated first before the || is brought into the mix. In this case, the || warning isn't thrown like it was above.


In reply to Re: Perldoc's explanation of the difference between '&&' and 'and' has me confused by stevieb
in thread Perldoc's explanation of the difference between '&&' and 'and' has me confused by LittleJack

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.