in reply to Re: Method chain object with easy syntax
in thread Method chain object with easy syntax
I don't know any reasons why this class can be useful in real life (i.e. production code). I wrote it more for learning perl then for actuall using it. Anyway, as I've mentioned, this technique could be useful for extending Switch or Quantum::Superpositions.
As for the semantics of $o->$m, you are right. It does inherit, and it does accept a stringified glob.
Btw, I think you're playing with fire when you dosince $chain may change during the loop. I'd feel much safer if you made a local copy of the array.for (@$chain) { ... }
I disagree here. While the scalar $chain can change, it can point to a different array later, the scalar itself is fetched only once. The important point is that the contents of the array it points to at start doesn't change, and that is true.
Also, it is easy to verify that the implementation is reentrant with a code like this:
#!perl use warnings; use strict; use IO::Handle; { package Object::MethodChain; use overload q[""], "__Set_MethodChain__"; AUTOLOAD { my $self = shift; my $class = ref($self) || $self; my @new = ref($self) ? @$self : (); our $AUTOLOAD =~ /.*::(.*)/s or die "error: invalid method name"; push @new, {"method", $1, "args", \@_}; bless \@new, $class; } our $chain; sub __Set_MethodChain__ { $chain = $_[0]; "Object::MethodChain::__Call_MethodChain__"; } sub __Call_MethodChain__ { my $r = $_[0]; for my $pair (@$chain) { my($method, $args) = @$pair{"method", "args"}; $r = $r->$method(@$args); } $r; } DESTROY { } } { package AnObj; sub new { bless [], $_[0]; } sub foo { my $c = Object::MethodChain->print("just "); STDOUT->$c; $_[0]; } sub bar { $_[1] = "ack"; OtherObj->new("erl h"); } } { package OtherObj; sub new { bless [$_[1]], $_[0]; } sub baz { print "anot", $_[1], $_[0][0]; "er,\n"; } } { my $f = "foo"; my $c = Object::MethodChain->new->$f->bar(my $v)->baz("her p"); my $n = AnObj->$c; print $v, $n; sub new { bless [], $_[0]; } sub foo { my $c = Object::MethodChain->print("just "); STDOUT->$c; $_[0]; } sub bar { $_[1] = "ack"; OtherObj->new("erl h"); } } { package OtherObj; sub new { bless [$_[1]], $_[0]; } sub baz { print "anot", $_[1], $_[0][0]; "er,\n"; } } { my $f = "foo"; my $c = Object::MethodChain->new->$f->bar(my $v)->baz("her p"); my $n = AnObj->$c; print $v, $n; } __END__
Update: In the simple case, sub { $_[0]->m1(@a1)->m2(@a2) } is of course simpler, but if you want to build a chain of methods without the length of it known in advance, then the sub solution can be more difficult.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Method chain object with easy syntax
by ihb (Deacon) on Apr 20, 2005 at 11:33 UTC | |
by ambrus (Abbot) on Apr 20, 2005 at 20:05 UTC |