Showing posts with label perl issues solved. Show all posts
Showing posts with label perl issues solved. Show all posts

Tuesday, December 08, 2009

Operator Precedence

It's that time again when I mention something that's already in the perldocs; this one is about operator precedence. Anyway today I found out that something like
my @a = qw(1);
print 'Yippeee!' if ( ! scalar(@a) >= 2 );
What does this print out? Yippeee!? Nope. The problem here is operator precedence. You may read it as the count of @a being greater than or equal to 2 and negate this (after all that's what ! normally means). Well what actually gets evaluated is ! count and then if this result is >= 2. Possible solutions to this are
print 'Yippeee!' if ( ! (scalar(@a) >= 2) );
print 'Yippeee!' if ( scalar(@a) < 2);
So the first deals with it by adding () to make sure the evaluation order is respected, the second replaces it for a more logical test.

What is the take home message? Everything in Perl has a precedence order.