Ovid (publius_ovidius) wrote,
Ovid
publius_ovidius

  • Mood:

Geek Alert: Perl

Another geek entry you can disregard.

I've fundamentally altered the way Perl functions and, if my code works, it's a strong change for the better.

Before, if you wanted to overload a method as both an accessor and mutator and ensure that your method would be called correctly, you had to do something like this:

sub name {
    my $self = shift;
    if (1 == @_ && ! ref $_[0]) {
        $self->{name} = shift;
        return $self;
    }
    elsif (! @_) {
        return $self->{name};
    }
    else {
        croak "Unknown arguments to name()";
    }
}

What the hell is that? Isn't Perl supposed to be more concise than other languages? In fact, here's how something similar would look in Java (it's impossible to duplicate this exact functionality in Java because return types may not change):

public String name () {
    return name;
}

public String name(String name) {
    this.name = name;
    return name;
}

Well, now it looks like Java is more concise than Perl. That's awful! So I fixed it by writing a CPAN module named Sub::Signatures.

use Sub::Signatures qw/strict methods/;

# ...

sub name($self) {
    return $self->{name};
}

sub name($self, $name) {
    $self->{name} = $name;
    return $self;
}

This makes life much, much simpler.

Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 13 comments