in reply to How to call sub defined in a variable?

Initialize the array differently (ie with references to subs):
my @subs = (\&test, \&another_test, \&third_test); my $sub_i_want_to_call = $subs[rand(@subs)]; $sub_i_want_to_call->();

See perlreftut for more informations.

Update: fixed copy&paste error in the code, thanks to ww++ for noticing.

Replies are listed 'Best First'.
Re^2: How to call sub defined in a variable?
by Arunbear (Prior) on Jan 25, 2009 at 21:29 UTC
    Or using the distributive nature of referencing:
    my @ary = \( &test, &another_test, &third_test ); my $sub_i_want_to_call = $ary[rand(@ary)]; $sub_i_want_to_call->();

      Thanks for suggestions, but I'm afraid that initializing the array with references instead of string literals would require lots of work in the context I'd need it.

      I actually stumbled upon this, but it relies on no strict 'refs', and I'm left wondering if there's a way to do something similiar with use strict?

      my @ary = qw( test another_test third_test ); my $sub_i_want_to_call = $ary[rand(@ary)]; { no strict 'refs'; &{$sub_i_want_to_call}; }
        yes, use the names as lookups into the symbol table, e.g.
        use strict; use warnings; sub test { print "something"; } sub another_test { print "something else"; } sub third_test { print "another unimaginative statement"; } $\ = "\n"; my @ary = qw( test another_test third_test ); my $sub_i_want_to_call = $main::{$ary[rand(@ary)]}; $sub_i_want_to_call->();
        See perlmod for the gory details of how it works.
        &{$sub_i_want_to_call};
        You probably want that to be &{$sub_i_want_to_call}(); (or the equivalent $sub_i_want_to_call->()). Subroutine calls with & but without parens give the callee direct access to the caller's @_, including the ability to modify it:
        $ perl -w sub foo { my $foo = shift } sub bar { &foo; warn @_ } bar("baz","quux","\n"); __END__ quux