Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options


by graff (Chancellor)
on May 14, 2006 at 06:22 UTC ( #549297=note: print w/replies, xml ) Need Help??

in reply to AND OR

Another similarity between perl and shell (common to C as well), is that the second expression will not be evaluated at all if the first expression "answers the question". This matters when the second expression has side effects. Some trivial examples:
sub f0 { return 0 } sub f1 { return 1 } if (( my $x = f1() ) && ( my $y = f1() )) # true, and both variables are set to 1 if (( my $x = f0() ) && ( my $y = f1() )) # false, $x is set to 0, $y is undef if (( my $x = f0() ) || ( my $y = f1() )) # true, $x is set to 0, $y is set to 1 if (( my $x = f1() ) || ( my $y = f1() )) # true, $x is set to 1, $y is undef
As in shell usage, this can be used to good effect, to perform (or skip) an action based on the outcome of previous action. (It can also be a trap for the unwary.)

Replies are listed 'Best First'.
Re^2: AND OR
by davidrw (Prior) on May 14, 2006 at 14:19 UTC
    (for keyword or further-search purposes) that behavior is dubbed "short-circuiting"

    And i'll toss in a good C example (avoid method calls on undef/null):
    int *x; if(ptr != NULL && *ptr==5){ ... } if( objPtr != NULL && objPtr->foo() ){ ... } # extended to perl: my $obj = Foo::Bar->new(); if( $obj && $obj->blah() ){ ... }
    Update: added parens for ->foo()

      Heh, you hit a C pet peave of mine. This:

      if( objPtr != NULL && objPtr->foo ){ ... }

      doesn't actually call any methods. You need objPtr->foo() for that. And the ANSI C committee should have made the "&" for getting a pointer to a method mandatory instead of optional and discouraged, as needing to do that is relatively rare, rarer than the mistake of not realizing that C requires the parens unlike several other quite similar languages. Further, this particular mistake usually results in compiler output that is quite difficult to diagnose, IME.

      - tye        

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://549297]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2023-09-26 19:28 GMT
Find Nodes?
    Voting Booth?

    No recent polls found