in reply to Re^4: Modules for autogenerating accessor/mutator methods
in thread Modules for autogenerating accessor/mutator methods

Could you please explain a bit the AUTOLOAD magic? I don't get it :)
  • Comment on Re^5: Modules for autogenerating accessor/mutator methods

Replies are listed 'Best First'.
Re^6: Modules for autogenerating accessor/mutator methods
by tlm (Prior) on Jun 05, 2005 at 00:10 UTC

    It goes something like this:

    sub AUTOLOAD { my $self = $_[ 0 ]; ( my $name = our $AUTOLOAD ) =~ s/.*:://; return if $name eq 'DESTROTY'; die "Unknown field: $name" unless exists $OK_FIELDS{ $name }; return @_ ? $self->{ $name } = shift : $self->{ $name }; }
    As you can infer from the above, this version assumes that the instances of this class are implemented as hash refs. However, I don't like using AUTOLOAD when I have a lot of inheritance going on (but then, I don't use inheritance much).

    I've seen many descriptions of this technique. You can find one in this section of perltoot. Also, The Perl Cookbook, the Alpaca book, Object Oriented Perl discuss the use of AUTOLOAD to generate accessors. I'm sure this list is far from exhaustive.

    the lowliest monk

      Thanks, I'll look into the docs. However I'm too young in OOP to try anything like this at the moment :)
Re^6: Modules for autogenerating accessor/mutator methods
by Fletch (Bishop) on Jun 04, 2005 at 22:50 UTC

    You setup a constant or package variable or what not that has a list of what your member names are. You then write a sub AUTOLOAD { ... } which looks to see if $AUTOLOAD is in that list and if so maps it into retrieving (or setting if given argument(s)) $self->{"_$AUTOLOAD"} as appropriate (possibly generating a coderef which does the same thing and assigning that to the correct glob so AUTOLOAD is bypassed the next time).

    --
    We're looking for people in ATL