Skip to Content
Perl Best Practices
book

Perl Best Practices

by Damian Conway
July 2005
Intermediate to advanced
544 pages
13h 8m
English
O'Reilly Media, Inc.
Content preview from Perl Best Practices

Chapter 8. Built-in Functions

Bloody instructions which, being taught, return to plague their inventor

William ShakespeareMacbeth, Act 1, Scene 7

The single most important recommendation about Perl's built-in functions is also the simplest: use them.

If Perl already provides a way to solve your problem, and that way is integrated into the language itself, then it doesn't make sense to reinvent it. It's likely that Perl's built-in solution is faster and far better debugged than anything you'll have time to write yourself.

However, some of Perl's built-in functions are sufficiently complex, and their behaviour sufficiently subtle, that there are still right and wrong ways to use them. This chapter explores some of these ways.

Sorting

Don't recompute sort keys inside a sort.

Doing expensive computations inside the block of a sort is inefficient. By default, the Perl interpreter now uses merge-sorting to implement sort[39], which means that every sort will call the block O(N log N) times. For example, suppose you needed to set up a collection of script files for binary-chop searching. In that case, you might need to sort a set of scripts by their SHA-512 digests. Doing that the obvious way is needlessly slow, because each script is likely to be re-SHA'd several times:

use Digest::SHA qw( sha512 );

# Sort by SHA-512 digest of scripts
@sorted_scripts
    = sort { sha512($a) cmp sha512($b) } @scripts;
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.
Start your free trial

You might also like

Modern Perl Best Practices

Modern Perl Best Practices

Damian Conway
Perl in a Nutshell, 2nd Edition

Perl in a Nutshell, 2nd Edition

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour

Publisher Resources

ISBN: 0596001738Supplemental ContentErrata