#!/usr/bin/perl package AccessMutate; # Silly package which returns old values # when attributes are mutated sub new { bless {}; } sub foo { my $self = shift; return $self->{foo} unless @_; my $old = $self->{foo}; $self->{foo} = shift; $old; } sub bar { my $self = shift; return $self->{bar} unless @_; my $old = $self->{bar}; $self->{bar} = shift; $old; } package C::P::MC; sub new { my $class = shift; my $obj = shift; bless \shift, $class; } # Call the object's method. If called # in scalar context, returns the proxy # object. If called in list context, returns # object, and return value. # (Update - drawback: assumes # that the method returns a scalar.., could # probably be fixed with some wantarray logic) sub AUTOLOAD { my $self = shift; my $obj = $$self; (my $method = $AUTOLOAD) =~ s/.*:://; my $ret = $obj->$method(@_); return $obj, $ret, $self; } sub DESTROY { 1 } package main; use strict; use warnings; # Return AM object my ($obj1) = C::P::MC ->new(AccessMutate->new) ->foo(3) ->bar(2); print $obj1->foo,"\n"; print $obj1->bar,"\n"; # Return CPMC object my $obj2 = C::P::MC ->new(AccessMutate->new) ->foo(3) ->bar(2); my (undef, $foo) = $obj2->foo; my (undef, $bar) = $obj2->bar; print "$foo $bar\n";