[Chicago-talk] Dynamic method call

Jay Strauss me at heyjay.com
Thu Nov 6 11:15:08 CST 2003


I started off doing:
my $sub = __PACKAGE__->can( $method );

but figured I'd get back a Package::Subname (class), and not the object I'm
currently using, though I must admit I didn't check to see what I was
getting back.

I'll try
> my $sub = $object->can( $method );

and see what I get back.  I need $self in the method I call, not sure it I
do:
my $sub = $object->can( $method );
&$sub(@arg);

if I can:
my $self = shift

once I'm in the function

Like I said, I'll try it
Jay

----- Original Message ----- 
From: "Steven Lembark" <lembark at jeeves.wrkhors.com>
To: "Chicago.pm chatter" <chicago-talk at mail.pm.org>
Sent: Thursday, November 06, 2003 10:45 AM
Subject: Re: [Chicago-talk] Dynamic method call


>
>
> -- Jay Strauss <me at heyjay.com>
>
> > How do I call a method, where a variable contains the method name?
> >
> > my $method = "do_something";
> > $self->$method;
>
> The "can" operator returns a subroutine referent if the given
> de-reference is capable of doing something. It can take an
> object or package name as the object and the sub name as an
> argument. If the given inheritence tree can do the thing you
> get back a referent (true) if not you get back undef (false).
>
> Any of:
>
> my $sub = $object->can( $method );
>
> my $sub = $package->can( $method );
>
> my $sub = __PACKAGE__->can( $method );
>
> will work.
>
>
> I use this heavily for dispatching initializers:
>
> my $item = shift;
>
> if( my $init = $item->can('init') )
> {
> $init->( $item )
> }
> else
> {
> my $type = ref $item || $item;
>
> carp "Bogus $item: ($type) cannot 'init'";
> }
>
> For your example:
>
> {
> my $item = shift;
> my $name = shift;
>
> my $call = $item->can( $name )
> or croak "Bogus item: cannot $name";
>
> my $result = $call->( $item );
>
> ...
> }
>
> will do what you were looking for.
>
> --
> Steven Lembark                               2930 W. Palmer
> Workhorse Computing                       Chicago, IL 60647
>                                             +1 888 359 3508
> _______________________________________________
> Chicago-talk mailing list
> Chicago-talk at mail.pm.org
> http://mail.pm.org/mailman/listinfo/chicago-talk
>
>




More information about the Chicago-talk mailing list