SPUG: Choosing an object's method at runtime
Sanford Morton
smorton at pobox.com
Thu May 25 10:03:08 CDT 2000
Thanks for the many helpful comments on runtime method choice. A
natural followup question is:
> I'm storing a list of methods in an array
>
> @methods = qw (go stop);
>
> which I'd like to call on an object which I know has those methods
>
> $p->$methods[0]();
>
> But this generates a syntax error, and I can't find a combination of
> braces which doesn't. What does work is a temporary variable:
>
> $meth = $methods[0];
> $p->$meth();
Damian Conway wrote privately that Perl's lexer doesn't permit what I
had wanted to do, since it requires a simple variable immediately
followed by a parenthesis in this construct. A compact expression is
$p->$_() for $methods[0];
Thanks again for all your comments.
Sandy Morton
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
POST TO: spug-list at pm.org PROBLEMS: owner-spug-list at pm.org
Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
For Subscriptions, Email to majordomo at pm.org: ACTION spug-list EMAIL
Replace ACTION by subscribe or unsubscribe, EMAIL by your Email address
More information about the spug-list
mailing list