Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

BooK (2612)

BooK
  {book} {at} {cpan.org}
http://paris.mongueurs.net/
Yahoo! ID: philippe_bruhat (Add User, Send Message)

Obfuscation [plover.com]. Pink [axis-of-aevil.net]. HTTP::Proxy [cpan.org]. YEF [yapceurope.org]. Fishnet [perl.org]. Kapow [cpan.org]. Cog's [perl.org] bitch [cpan.org]. Invitation [perl.org]. White [perl.org] Camel [perl.org]. Nuff' said.

Journal of BooK (2612)

Sunday April 18, 2004
09:40 AM

Generating accessors

[ #18378 ]

After discovering AUTOLOAD, I wrote my accessors as (excerpt from Log::Procmail 0.05):

sub AUTOLOAD {
    # don't DESTROY
    return if $AUTOLOAD =~ /::DESTROY/;

    # fetch the attribute name
    $AUTOLOAD =~ /.*::(\w+)/;
    my $attr = $1;
    if ( $attr eq lc $attr ) {    # accessors are lowercase
        no strict 'refs';

        # create the method
        *{$AUTOLOAD} = sub {
            my $self = shift;
            @_ ? $self->{$attr} = shift: $self->{$attr};
        };

        # now do it
        goto &{$AUTOLOAD};
    }
}

This looks cargo-cultish, and I can't remember why I put that if ( $attr eq lc $attr ) line in the code.

Now I prefer generating the accessors from the beginning (this is an excerpt from Log::Procmail 0.06):

for my $attr (qw( from date subject size folder source ) ) {
    no strict 'refs';
    *{"Log::Procmail::Abstract::$attr"} = sub {
        my $self = shift;
        @_ ? $self->{$attr} = shift: $self->{$attr};
    }
}

I tend to prefer this way of doing things:

  • Adding a new accessors is as simple as adding its name to the list
  • No risk of AUTOLOADing the wrong method when doing a typo
  • All the methods exist from the beginning

What did I miss?

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • use base qw( Class::Accessor::Fast );
    __PACKAGE__->mk_accesors(qw( from date subject size folder source ));

    See: Class::Accessor [cpan.org]

  • Attribute::Property
    use Attribute::Property;

    package My::Class;
    sub foo : Property;
    sub bar : Property;
    sub baz : Property { /^\d+$/ }
    This has the advantage of being able to use them as lvalues, like in Perl 6:
    $foo->bar =~ s/foo/bar/;
    instead of:
    my ($temp = $foo->bar) =~ s/foo/bar/;
    $foo->bar($temp);