Skip to Content
Perl Hacks
book

Perl Hacks

by Chromatic, Damian Conway, Curtis Ovid Poe, Curtis (Ovid) Poe
May 2006
Beginner
298 pages
6h 51m
English
O'Reilly Media, Inc.
Content preview from Perl Hacks

Hack #36. Replace Bad Code from the Outside

Patch buggy modules without touching their source code.

Until computers finally decide to do what we mean, not what we say, programs will have bugs. Some you can work around. Others are severe enough that you have to modify source code.

When the bugs are in code you don't maintain and you don't have a workaround, Perl's dynamic nature can be an advantage. Instead of keeping local copies of externally managed code, sometimes patching that code from the outside is the simplest way to make your code work again.

The Hack

Imagine that you're building a large application that uses a hypothetical Parser module that, for whatever reason, calls exit( ), not die( ), when it fails. The relevant code might look something like:

package Parser;

sub parse
{
    my ($class, $text) = @_;
    validate_text( $shift );
    bless \\$text, $class;
}

sub validate_text
{
    my $text = shift;
    exit 1 unless $text =~ /^</;
}

1;

You might normally expect to use this module with code such as:

use Parser;

my $parser = eval { Parser->parse( 'some example text' ) };
die "Bad input to parser: $@\\n" if $@;

However because of the exit( ), your program will end. It may be perfectly legitimate that the text to parse in this example is invalid, so Parser can't handle it, but the exit( ) is just wrong—it gives you no opportunity to alert the user or try to fix the problem. If validate_text( ) were a method, you could subclass the module and override it, but you don't have this option.

Fortunately, ...

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

Perl Debugged

Perl Debugged

Peter Scott, Ed Wright
Perl 6 Deep Dive

Perl 6 Deep Dive

Andrew Shitov
Learning Perl 6

Learning Perl 6

brian d foy
Perl by Example

Perl by Example

Ellie Quigley

Publisher Resources

ISBN: 0596526741Supplemental ContentErrata Page