Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re^2: Invoking a method whose name is computed

by afoken (Prior)
on Oct 02, 2012 at 05:43 UTC ( #996802=note: print w/ replies, xml ) Need Help??


in reply to Re: Invoking a method whose name is computed
in thread Invoking a method whose name is computed

You invoke Foo::bar_baz as function, not as method. For a method call, the object / class name implicitly added by perl is missing, so you have to add it manually:

Class->can("prefix_$name")->(Class,'first argument'); $object->can("prefix_$name")->($object,'first argument');

Hardly DRY. I prefer "wasting" a variable for composed method names:

my $method="prefix_$name"; Class->$method('first argument'); $object->$method('first argument');

Alexander

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)


Comment on Re^2: Invoking a method whose name is computed
Select or Download Code
Replies are listed 'Best First'.
Re^3: Invoking a method whose name is computed
by GrandFather (Sage) on Oct 02, 2012 at 20:39 UTC

    An advantage of the "wasted variable" (I prefer to think it is an "intelligently used variable") is that you can perform a little validation:

    my $object = bless {hi => 'hello'}; for my $suffix ('x', 'y') { my $method = $object->can("prefix_$suffix"); $object->$method() if $method; } sub prefix_x { my ($self) = @_; print "$self->{hi} world\n"; }

    Update: elaborate code to better show intent.

    True laziness is hard work

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://996802]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (14)
As of 2015-07-30 16:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (273 votes), past polls