Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.

Re: Dynamically constructed function calls

by itub (Priest)
on Nov 03, 2004 at 23:53 UTC ( #405057=note: print w/replies, xml ) Need Help??

in reply to Dynamically constructed function calls

From perldoc perlop
Otherwise, the right side is a method name or a simple scalar variable containing either the method name or a subroutine reference, and the left side must be either an object (a blessed reference) or a class name (that is, a package name). See perlobj.

This means that you can't have a string or an expression as a method name. It has to be a simple scalar. So if you do the following, everything should work fine:

my $method = "prefix_$key"; $f->$method($atr);

Replies are listed 'Best First'.
Re^2: Dynamically constructed function calls
by dpuu (Chaplain) on Nov 04, 2004 at 01:07 UTC
    It has to be a scalar, but it doesn't need to be a variable. You can say
    However, using a variable is probably clearer.

    Update: added the missing '$' pointed out by ikegami

    Opinions my own; statements of fact may be in error.

      I've toyed with the idea of making $object->do {expression-yielding-method-name} work. Right now it gives a syntax error.

      Of course, you can do something pretty close by just having a do method:

      sub foo { print "in foo" } sub do { my $self = shift; my $meth = shift; $self->$meth(@_) } $object->do("foo", @args);
        It would have to be something that has scalar context applied to it. That would yield some neat obfu.
        package Foo; sub new { bless {}, shift } *$_ = sub { my ($self, $arg) = @_; print "I am $_ $arg.\n" } for 1 .. +5; package main; my $foo = Foo->new; $foo->do { @ARGV }( 'world' );

        Blammo! :-)

        Being right, does not endow the right to be rude; politeness costs nothing.
        Being unknowing, is not the same as being stupid.
        Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
        Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

      You're missing a $. It should be $f->${\("prefix_$key")}($atr);

      Nice trick, I had never thought about that! :-)

Log In?

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2023-12-11 18:00 GMT
Find Nodes?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?

    Results (41 votes). Check out past polls.