Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re^2: Invoking a method whose name is computed

by afoken (Abbot)
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');


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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://996802]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2018-05-23 05:34 GMT
Find Nodes?
    Voting Booth?