Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Any difference in conditionals?

by pboin (Deacon)
on Apr 27, 2004 at 16:15 UTC ( [id://348559]=note: print w/replies, xml ) Need Help??


in reply to Any difference in conditionals?

The way you wrote it, no (real) difference, 'cause you're just accessing the values in $x1 and $x2. If, on the other hand, you were doing something like incrementing one of them, they are *very* different.

The logical AND is lazy. By that I mean when perl is doing the test, if the first half evaluates to false, the second half doesn't get evaluated at all. It can get you into trouble if you don't know to expect it.

In method #2 below, the $x1 gets incrmented and $x2 doesn't.

#!/usr/bin/perl use strict; my $x1 = 1; my $x2 = 1; print "\$x1 starts as $x1 and \$x2 starts as $x2.\n"; # method 1 if ($x1++) { if ($x2++) { print "We incremented \$x1 to $x1 and \$x2 to $x2.\n"; } } undef $x1; undef $x2; print "Undefine them both...\n"; #method 2 if ($x1++ && $x2++){ print "Shouldn't ever get here!\n"; } print "Now, we incremented \$x1 to '$x1' and \$x2 is still '$x2'.\n";

Replies are listed 'Best First'.
Re: Re: Any difference in conditionals?
by kelan (Deacon) on Apr 27, 2004 at 16:51 UTC

    Your tests aren't equivalent. In method 1, both variables start out as 1. In method 2, both variables start undefined. If you start with the same state in both tests, the results will be identical, both for the 'start as 1' case and the 'start undefined' case.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (6)
As of 2024-04-24 11:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found