in reply to Re^2: How to call sub defined in a variable?
in thread How to call sub defined in a variable?

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}; }

Replies are listed 'Best First'.
Re^4: How to call sub defined in a variable?
by Arunbear (Prior) on Jan 25, 2009 at 21:44 UTC
    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.

      Thanks, this is exactly what I was looking for. =)

      The OO version looks interesting too though, and I might end up using it instead.

      Thanks to all of you! :)

Re^4: How to call sub defined in a variable?
by ysth (Canon) on Jan 25, 2009 at 23:59 UTC
    &{$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