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 #94. Add Your Own Perl Syntax

Shape the language as you see fit.

Perl is a great language, but it's certainly not perfect. Sometimes bits and pieces of the implementation poke through. Sometimes the natural solution to a problem doesn't fit the existing language very well at all. Some problems are easier if you can just define them away.

Sometimes the simplest solution is just to change the syntax of Perl.

For example, it's frustrating that you can't specify a simple parameter list for a subroutine (without some gyrations, as in "Autodeclare Method Arguments" [Hack #47]):

my @NUMERAL_FOR    = (0..9,'A'..'Z');

sub convert_to_base($base, $number)
{
    my $converted  = "";
    while ($number > 0)
    {
        $converted = $NUMERAL_FOR[$number % $base] . $converted;
        $number    = int( $number / $base);
    }
    return $converted;
}

Instead, you have to do it yourself:

sub convert_to_base
{
    my ($base, $number) = @_;   # <-- DIY parameter list

    my $converted       = ''
    while ($number > 0)
    {
        $converted      = $NUMERAL_FOR[$number % $base] . $converted;
        $number         = int( $number / $base);
    }

    return $converted;
}

This is why far too many people just write:

sub convert_to_base
{
    my $converted  = '';

    while ($_[1] > 0)
    {
        $converted = $NUMERAL_FOR[$_[1] % $_[0]] . $converted;
        $_[1]      = int( $_[1] / $_[0]);
    }

    return $converted;
}

buying themselves a world of future maintenance pain in the process.

The Hack

Although Perl may not be perfect, it is perfectable. For example, recent versions of Perl provide a way to grab your program's source code before ...

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