Slash Boxes
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} {at} {}
Yahoo! ID: philippe_bruhat (Add User, Send Message)

Obfuscation []. Pink []. HTTP::Proxy []. YEF []. Fishnet []. Kapow []. Cog's [] bitch []. Invitation []. White [] Camel []. 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):

    # 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.
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 []

  • 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/;