Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

dynamic methods with variables

by jorg (Friar)
on Jul 30, 2003 at 12:33 UTC ( [id://279153]=perlquestion: print w/replies, xml ) Need Help??

jorg has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,
This post describes how one can achieve dynamic method calling using scalars.

my $foo = Obj->new; for (qw( create init add )) { $foo->$_(); # note -- $foo->$_ will not work, ()'s needed }

This approach works fine as long as you're not passing parameters along.
I want to do something along the lines of :

my $method = 'Quantize'; my $parameters = qw (colorspace=>'gray' compression=>'none'); my $image = Image::Magick->new; $image->Read('/share/colortransition.jpg'); $image->${method}($parameters); $image->write(filename=>'/share/graytransition.jpg');

... but i'm getting Argument "colorspace=>'gray'" isn't numeric in subroutine entry at im.pl line 10.Now this tells me that probably the parameter passing works but it's expecting a numeric parameter and the "qw" garbles it somehow. Is my observation correct?

Jorg

"Do or do not, there is no try" -- Yoda

Replies are listed 'Best First'.
Re: dynamic methods with variables
by liz (Monsignor) on Jul 30, 2003 at 12:47 UTC
    You're mixing metaphors ;-)

    Try:

    my $parameters = {colorspace=>'gray', compression=>'none'};
    Seems you're mixing up qw() with the anonymous hash reference constructor {}.

    Liz

Re: dynamic methods with variables
by broquaint (Abbot) on Jul 30, 2003 at 12:48 UTC
    You need to drop the qw() and change $parameters to an array e.g
    my @parameters = (colorspace = >'gray', compression = >'none');
    Because as it stood $parameters was being assigned compression=>'none' as your code really looked like this
    my $parameters = (q[colorspace=>'gray'], q[compression=>'none']);
    See. perlop for more info on the workings of qw().
    HTH

    _________
    broquaint

Re: dynamic methods with variables
by jorg (Friar) on Jul 30, 2003 at 13:11 UTC
    dow ...
    I could've stared at this for ages without spotting it ..

    Thanks!

    Jorg

    "Do or do not, there is no try" -- Yoda

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://279153]
Approved by valdez
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2024-04-16 23:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found