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 ...

Get Perl Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.