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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.