Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

Optimize Perl

By Martin C. Brown
2005-04-11


Using Short Circuit Logic

Related to the sort operation is how to work through a list of alternative values. Using many if statements can be incredibly time consuming. For example, look at the code in Listing 7.

Listing 7. Making a choice
if ($userchoice > 0)

{
$realchoice = $userchoice;
}
elsif ($systemchoice > 0)
{
$realchoice = $systemchoice;
}
else
{
$realchoice = $defaultchoice;
}
Aside from the waste of space in terms of sheer content, there are a couple of problems with this structure. From a programming perspective, it has the issue that it never checks if any of the variables have a valid value, a fact that would be highlighted if warnings were switched on. Second, it has to check each option until it gets to the one it wants, which is wasteful, as comparison operations (particularly on strings) are time consuming. Both problems can be solved by using short circuit logic.

If you use the logical || operator, Perl will use the first true value it comes across, in order, from left to right. The moment it finds a valid value, it doesn't bother processing any of the other values. In addition, because Perl is looking for a true value, it also ignores undefined values without complaining about them. So we can rewrite the above into a single line:

$realchoice = $userchoice || $systemchoice || $defaultchoice;

If $userchoice is a true value, Perl doesn't even look at the other variables. If $userchoice is false (see Table 1), then Perl checks the value of $systemchoice and so on until it gets to the last value, which is always used, whether it's true or not.

Table 1. $userchoice values
Value	                                       Logical value

Negative number True
Zero False
Positive number True
Empty string False
Non-empty string True
Undefined value False
Empty list (including hashes) False
List with at least one element (including hashes) True


Tutorial Pages:
» Squeeze the Most From Your Code
» Sloppy Programming, Sloppy Performance
» Approaching Optimization
» Use References
» String Handling
» Loops
» Sorts
» Using Short Circuit Logic
» Use AutoLoader
» Using Bytecode and the Compiler Back Ends
» Other Tools
» Putting it All Together
» Resources


First published by IBM DeveloperWorks


 | Bookmark
Related Tutorials:
» Random subroutines in Perl
» Log Script Use
» Creating Perl Modules for Web Sites
» Bit Vector, Using Perl Vec
» Build a Perl/CGI Voting System
» Perl Range Operator

Ask A Question
characters left.