Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^2: Invoking a method whose name is computed

by afoken (Monsignor)
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". ;-)

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 exploiting the Monastery: (10)
As of 2016-06-29 15:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My preferred method of making French fries (chips) is in a ...











    Results (384 votes). Check out past polls.