In addition to "no strict 'refs'" (which would be my first suggestion), there are a few other ways with various advantages.
If you know all the subs you want to reference this way, you could use a dispatch table.
my %sub_named = ( this => \&this, that => \&that, ); my $ref = 'this'; my $x; if ( exists $sub_named{ $ref } ) { $x = $sub_named{ $ref }->(); } else { # error, no sub named $ref }
You could even make the dispatch table dynamic using eval.
my @sub_list = qw( this that ); my %sub_named = map { $_ => eval "\\&$_" } @sub_list; # etc.
This way, you can see what subs are available before trying to take a leap into one of them.
You can also use eval directly.
use English '-no_match_vars'; my $ref = 'this'; my $x = eval "&$ref()"; if ( my $error_message = $EVAL_ERROR ) { if ( $error_message =~ /^Undefined subroutine / ) { # a dispatch table would have caught this } }
This is actually kind of clumsy. On the other hand, if you're not using a dispatch table, you might want to wrap calls in an eval anyway to catch that moment when you try to call a sub that doesn't exist.
I haven't run and tested the code here, but it should work.
In reply to Re: variable reference to subroutine while "strict"
by kyle
in thread variable reference to subroutine while "strict"
by halfcountplus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |