While most of the work of programming may simply be getting your program working properly, you may find yourself wanting more bang for the buck out of your Perl program. Perl’s rich set of operators, data types, and control constructs are not necessarily intuitive when it comes to speed and space optimization. Many trade-offs were made during Perl’s design, and such decisions are buried in the guts of the code. In general, the shorter and simpler your code is, the faster it runs, but there are exceptions. This section attempts to help you make it work just a wee bit better.

If you want it to work a lot faster, you can play with the Perl compiler backend described in Chapter 16, or rewrite your inner loop as a C extension (which we don’t cover in this book). However, before you do any work, you should profile your program (see Chapter 17) to see whether there’s something simple you can adjust first.

Note that optimizing for time may sometimes cost you in space or programmer efficiency (indicated by conflicting hints below). Them’s the breaks. If programming was easy, they wouldn’t need something as complicated as a human being to do it, now would they?

Time Efficiency

  • Use hashes instead of linear searches. For example, instead of searching through @keywords to see whether $_ is a keyword, construct a hash with:

    my %keywords;
    for (@keywords) {

    Then you can quickly tell if $_ contains a keyword by testing $keyword{$_} for a nonzero value.

  • Avoid subscripting when ...

Get Programming Perl, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.