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

Hello again Monks...
Are there any circumstances under which Perl will interpret a scalar variable as actual Perl? This
use warnings; use strict; my @commands = 'print "hello", print "world"'; foreach my $command(@commands) { $command; }
yields the message "Useless use of private variable in void context at script.pl line 6".

Replies are listed 'Best First'.
Re: Interpret array elements as actual Perl?
by Fletch (Bishop) on May 28, 2004 at 16:59 UTC

    perldoc -f eval

      neat
Re: Interpret array elements as actual Perl?
by calin (Deacon) on May 28, 2004 at 18:24 UTC

    You'd better go with an array of anonymous subs, IMHO.

    my @commands = ( sub {print "hello\n"}, sub {print "world\n"} ); foreach my $command (@commands) { &{$command}; }

      Isn't this better written as:

      use strict; my @commands = ( sub {print "hello\n"}, sub {print "world\n"}, ); foreach my $command (@commands) { $command->(); # Or use args like this: $command->($arg1,$arg2); }
      (Using subname() instead of &subname)

        I think it's a matter of taste. It may look cleaner in a cascaded dereference construct, but I tend to avoid it as much as I can for religious reasons (it looks OOPish ;) )

        You can pass arguments with the ampersand syntax too: &$command ($arg1, $arg2);

        Update: There are issuse with a bare & call and @_, see code:

        $ perl sub foo { my $x = sub {print "@_"}; &{$x}; } foo qw/bar baz/; ^D bar baz

        If you don't want to transfer @_ use &{$x} (); (or $x->();)