http://qs321.pair.com?node_id=107171

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

I was trying to patch some buggy code when I came across some syntax that I thought was a bit odd and certainly doesn't return results that I expect. Here's the smallest test case I could replicate:

perl -e '$x=1;print 1 if $x or print 0'

That prints 1, just as I would expect, despite the syntax being a bit odd. However, if I set $x to a false value, it prints 01. Why the heck does it print the zero and then turn around and print the one, anyway? Since print, in this context, should always return a true value, shouldn't this short-circuit and not do both prints? And wouldn't the first print be skipped by the "if $x" check?

If I change this slightly:

my $x = 0; &one if $x or &zero; sub one { print "one"; 1; } sub zero { print "zero"; 0; }

That only prints "zero". I have an explicit return of false in &zero, but all in all, I'm just not quite grokking this.

Cheers,
Ovid

Vote for paco!

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.