#!/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 | |
by rpc (Monk) on Jan 18, 2001 at 00:30 UTC | |
Re: accessor/mutator with AUTOLOAD
by Nooks (Monk) on Feb 11, 2001 at 08:40 UTC |