Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Perldoc's explanation of the difference between '&&' and 'and' has me confused

by LittleJack (Beadle)
on Jul 05, 2021 at 04:38 UTC ( [id://11134647]=perlquestion: print w/replies, xml ) Need Help??

LittleJack has asked for the wisdom of the Perl Monks concerning the following question:

To quote:

Logical And

Binary "and" returns the logical conjunction of the two surrounding expressions. It's equivalent to && except for the very low precedence. This means that it short-circuits: the right expression is evaluated only if the left expression is true.

and then:

C-style Logical And

Binary "&&" performs a short-circuit logical AND operation. That is, if the left operand is false, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it is evaluated.

Maybe it's just me, but these things seem to be the same:

  • the right expression is evaluated only if the left expression is true.
  • if the left operand is false, the right operand is not even evaluated.

What am I missing?

Any real-life examples of how the two would behave differently gratefully received.

Update: Thanks everyone for your input, very helpful and I get it now.

Where do I put in a patch request for Perldoc to be improved though?

The sentence 'This means that it short-circuits: the right expression is evaluated only if the left expression is true.' appears to refer to the clause 'the very low precedence' in the previous sentence, i.e. 'Very low precedence means that the right expression is evaluated only if the left expression is true'.

  • Comment on Perldoc's explanation of the difference between '&&' and 'and' has me confused

Replies are listed 'Best First'.
Re: Perldoc's explanation of the difference between '&&' and 'and' has me confused
by stevieb (Canon) on Jul 05, 2021 at 05:04 UTC

    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.

Re: Perldoc's explanation of the difference between '&&' and 'and' has me confused
by haukex (Archbishop) on Jul 05, 2021 at 05:08 UTC
    Maybe it's just me, but these things seem to be the same

    They are the same in that regard, as the documentation you quoted says: "It's equivalent to && except for the very low precedence." The next section in the documentation, Logical or and Exclusive Or, explains why not, and, or, and xor are useful: for flow control. For example, if ( $x eq "x" ) { $y = "y" } can be written as $y = "y" if $x eq "x"; or $x eq "x" and $y = "y";, but not $x eq "x" && $y = "y";, because precedence messes that up. Another common place is open my $fh, '<', $filename or die "$filename: $!"; where || die would be wrong ("open" Best Practices), or for example I sometimes like to write if ( not ... ) {} instead of unless (...) {} because depending on the condition the former sometimes reads a little more easily.

Re: Perldoc's explanation of the difference between '&&' and 'and' has me confused (precedence)
by LanX (Saint) on Jul 05, 2021 at 05:16 UTC
Re: Perldoc's explanation of the difference between '&&' and 'and' has me confused
by AnomalousMonk (Archbishop) on Jul 05, 2021 at 05:35 UTC

    Deparsing (see O and B::Deparse) is a useful way to look at issues of precedence:

    Win8 Strawberry 5.8.9.5 (32) Mon 07/05/2021 1:12:59 C:\@Work\Perl\monks >perl -Mstrict -Mwarnings -l -MO=Deparse,-p my ($x, $y, $z) = qw(eks wye zee); print $x && $y && $z; print $x && $y and $z; # $z is useless ^Z Useless use of private variable in void context at - line 4. BEGIN { $/ = "\n"; $\ = "\n"; } use warnings; use strict 'refs'; (my($x, $y, $z) = ('eks', 'wye', 'zee')); print((($x && $y) && $z)); (print(($x && $y)) and $z); - syntax OK


    Give a man a fish:  <%-{-{-{-<

Re: Perldoc's explanation of the difference between '&&' and 'and' has me confused
by eyepopslikeamosquito (Archbishop) on Jul 05, 2021 at 08:24 UTC

      I agree in principle, but I tend to also use and and or in very complex expressions to be able to use less parens:

      if (($foo && ($bar || $zebra) && ($fox & $mask) && $option_x) || ($zul +y & $mask2 || $lion)) {

      =>

      if ($foo && ($bar || $zebra) && ($fox & $mask) && $option_x or $zuly & + $mask2 || $lion) {

      most often with line breaks. The "or" and "and" will be bold in my editors syntax highlighting making it even more clear what the logical groups are. YMMV.


      Enjoy, Have FUN! H.Merijn
        Honestly, I find this still pretty unreadable.

        Probably because it's a contrived example?

        If this actually was realworld code I'd add many line-breaks and comments for each line.

        Or even better break it down into speaking variables for sub-terms.

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11134647]
Approved by haukex
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2024-03-29 22:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found