Time Efficiency
Use hashes instead of linear searches. For example, instead of searching through
@keywordsto see whether$_is a keyword, construct a hash with:my %keywords; for (@keywords) { $keywords{$_}++; }Then you can quickly tell if
$_contains a keyword by testing$keyword{$_}for a nonzero value.Avoid subscripting when a
foreachor list operator will do. Not only is subscripting an extra operation, but if your subscript variable happens to be in floating point because you did arithmetic, an extra conversion from floating point back to integer is necessary. There’s often a better way to do it. Consider usingforeach,shift, andspliceoperations. Consider sayinguse integer.Avoid
goto. It scans outward from your current location for the indicated label.Avoid
printfwhenprintwill do.Avoid
$&and its two buddies,$`and$'. Any occurrence in your program causes all matches to save the searched string for possible future reference. However, once you’ve blown it, it doesn’t hurt to have more of them. Perl v5.10 introduced the per-match variables with the/p(see Chapter 5), so you don’t have to either suffer or give up features.Avoid using
evalon a string. Anevalof a string (although not of aBLOCK) forces recompilation every time through. The Perl parser is pretty fast for a parser, but that’s not saying much. Nowadays there’s almost always a better way to do what you want anyway. In particular, any code that usesevalmerely to construct variable names is obsolete since ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access