The Problem
Many programmers have a tendency to write code like this:
$color = "black";
if ($ENV{COLOR}) {
$color = $ENV{COLOR};
}
or:
if ($ENV{COLOR}) {
$color = $ENV{COLOR};
}
else {
$color = "black";
}
After all, this is the way we tend to think; it happens to be the way most languages work today. But Perl has a simpler and easier method for doing conditional variable initializations.
The Solution
$color = $ENV{COLOR} || "black";
That's much more readable, isn't it? You can clearly see the preferred value is $ENV{COLOR}, but if it's not set, the default value is "black". This works because Perl's AND and OR operators are "short circuit" operators - they will not evaluate the right-hand value, if the left-hand value satisfies the requirement.
Why It Works
The || symbol is the logical OR operator. Think about how OR works - it compares two true/false values and returns true if either one "or" the other is true. So, if you have a true value for the first value, is there any reason to ever look at the second value? No! You know for sure the return value should be true. Perl tries hard to run your code as fast as possible - if it knows the result of an OR operation after only looking at the left-hand value, it will stop evaluating that expression and move on to the next part of your code. This way, the value of $ENV{COLOR} is "returned" to the assignment statement if it contains anything, otherwise the right-hand part of the statement must be evaluated. Remember that any non-zero value is considered true, in Perl.
The Bottom Line
This kind of simplification can clean up your code dramatically, which is important, especially in very large programs. However, it is very language specific - you cannot use this syntax in C, shell scripts, or many other languages. Some people feel it's better to stick to syntaxes that are more common across many languages, so that a wider variety of programmers at their company might be able to support the code. (i.e. "don't do complicated things that only you understand!") If that's the case for you, then you should use the first 2 examples on this page instead. Understand your environment, and choose what is right for you.
Don't miss the latest perl tips and tricks!
Subscribe to our low-volume mailing list:
Privacy Policy
| Copyright © 2006 Fastech Learning LLC, all rights reserved. |
| Phone toll free 1-866-464-6688, Phoenix Metro area 480-895-6688 |
| Problem with this web site? please let us know |