Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

accessor/mutator with AUTOLOAD

by rpc (Monk)
on Jan 17, 2001 at 23:53 UTC ( #52582=snippet: print w/replies, xml ) Need Help??
Description: This AUTOLOAD sub is a general purpose accessor and mutator for data members of a class. It assumes the object is a blessed hashref. It's not as flexible as Class::Accessor, but eliminates the dependancy on an accessor/mutator module, or rolling your own.
#!/usr/bin/perl -w

package Foo;
use strict;

sub AUTOLOAD
{
    no strict qw(refs vars);
    my $pkg = __PACKAGE__;

    $AUTOLOAD =~ s/${pkg}:://;

    return if $AUTOLOAD eq 'DESTROY';

    if(exists $_[0]->{$AUTOLOAD}) {
        no strict 'refs';
        *{$AUTOLOAD} = sub {

            $_[1]    ?    $_[0]->{$AUTOLOAD} = $_[1]
                     :    $_[0]->{$AUTOLOAD};
        }
    } 
    else {
        die "Can't locate object method \"$AUTOLOAD\" via package \"$p
+kg\"";
    }
    
    &{$AUTOLOAD}(@_);    
}

sub new
{
    bless {foo => "bar"}, ref($_[0]) || $_[0];
}


package main;
use strict;

my $foo = new Foo;
print $foo->foo, "\n";
print $foo->foo("bas"), "\n";
print $foo->foo, "\n";

Update: Thanks to chipmunk for pointing out a regex problem.

Replies are listed 'Best First'.
Re: accessor/mutator with AUTOLOAD
by chipmunk (Parson) on Jan 18, 2001 at 00:26 UTC
        $AUTOLOAD =~ s/${pkg}::([^(?:::)]+)$/$1/; Woops. Extended regex syntax does not work inside a character class. (It wouldn't be a character class if it did.) [^(?:::)] will match any single character that is not an open paren, a question mark, a colon, or a close paren.

    It looks like you're trying to match a sequence of characters that does not include two colons in a row. This should work: s/${pkg}::((?:[^:]+|:(?!:))+)$/$1/; But I wonder if a simpler substitution would be more appropriate here: s/${pkg}:://;

      You're right. Thanks for pointing that out.
Re: accessor/mutator with AUTOLOAD
by Nooks (Monk) on Feb 11, 2001 at 08:40 UTC
    I did a similar thing with perl 5.6's lvalue subs about the same time this node was created. You can find a copy of Frog.pm on my work website.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: snippet [id://52582]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2023-02-05 14:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (31 votes). Check out past polls.

    Notices?