Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Class method names in a scalar variable

by rongrw (Acolyte)
on Dec 23, 2013 at 15:11 UTC ( [id://1068199]=perlquestion: print w/replies, xml ) Need Help??

rongrw has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

Is it possible to call a class method whose name is stored in a scalar variable? For example, consider the following code.

package Class_A; sub Meth_U { ... } sub Meth_V { ... } sub Meth_W { ... } sub Dump_SV { my $self = shift; foreach my $a qw( U V W ) { my $method = "Meth_" . $a; # Call the method whose name is kept in a variable. $self->$method->(); # DOES NOT WORK } }
Cheers, Ron.

Replies are listed 'Best First'.
Re: Class method names in a scalar variable
by LanX (Saint) on Dec 23, 2013 at 15:19 UTC
    yes, just wrong syntax:

    try $self->$method();

    ->Methods are always just strings which are messaged to the class to seek the appropriate sub.

    Cheers Rolf

    ( addicted to the Perl Programming Language)

Re: Class method names in a scalar variable
by tobyink (Canon) on Dec 23, 2013 at 15:28 UTC

    In addition to LanX's answer (which is correct), I'll point out that $self->$method->() is valid Perl; it just doesn't do what you want. $self->$method->() will call the method named in $method on the $self object; it then assumes that the method will return a coderef, and calls that coderef.

    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1068199]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (5)
As of 2024-04-19 12:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found