[Chicago-talk] Dynamic method call

Steven Lembark lembark at jeeves.wrkhors.com
Thu Nov 6 10:45:42 CST 2003



-- 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



More information about the Chicago-talk mailing list