Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

accessor/mutator with AUTOLOAD

by rpc (Monk)
on Jan 17, 2001 at 23:53 UTC ( [id://52582]=CUFP: print w/replies, xml ) Need Help??

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: CUFP [id://52582]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2024-03-28 19:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found