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

Let me try that again with some formatting 8)

I've got an array of commands like this:
@commands = ("add_node('W1')", "add_node('W2')", "add_edge('W2' => 'W1 +')");


that I want to use as method invokers in a loop like this:
use GraphViz; my $g = GraphViz->new(); foreach $command (@commands) { $g->$command; }

It doesn't seem to be working so I was wondering if there is something I have to do to dress up $command. I'm getting and error message like this:
Can't locate object method ")" via package "add_node('W1')"

Replies are listed 'Best First'.
Re: calling methods using a variable (FORMATTED)
by Fletch (Bishop) on Mar 22, 2002 at 03:40 UTC

    You can use a variable to specify just the method, not arguments. What you could do have an array of arrays and call thusly:

    my @commands = ( [ 'add_node', 'W1' ], [ 'add_node', 'W2' ], [ 'add_edge', 'W1', 'W2' ], ); use GraphViz; my $g = GraphViz->new(); foreach my $cur ( @commands ) { my $method = shift @{$cur}; $g->$method( @{ $cur } ); }
Re: calling methods using a variable (FORMATTED)
by chromatic (Archbishop) on Mar 22, 2002 at 05:13 UTC
    @commands = ( sub { $_[0]->add_node('W1') }, sub { $_[0]->add_node('W2') }, sub { $_[0]->add_edge( W2 => 'W1' ) }, ); use GraphViz; my $g = GraphViz->new(); foreach my $command (@commands) { $command->($g); }