Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^2: Invoking a method whose name is computed

by afoken (Parson)
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
Re^3: Invoking a method whose name is computed
by GrandFather (Cardinal) 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 cooling their heels in the Monastery: (6)
As of 2014-09-18 02:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (105 votes), past polls