Others have warned you that this is a bad idea, though no one as of yet has explained why.

If someone malicious guesses the name of your subroutine, he can execute anything at will. That could be bad.

More likely, if there's a typo, it could call an undefined subroutine, which will have unexpected results. strict mode warns you about typos and other hazardous constructs to reduce these nasty surprises.

The oddly-named Re: use slack; presents one solution. Another would be to call UNIVERSAL::can() on an object, if you're using an object.

Otherwise, you might look through the package symbol table for a named glob, then check it for a code reference and call the code that way. It still requires disabling strict references, but it is a little safer and you can earn a Perl merit badge for knowing how:

sub get_coderef { my $subname = shift; my $coderef; no strict 'refs'; $coderef = *{"$subname"}{CODE}; return $coderef if ($coderef and defined(&$coderef)); }
Add the following to test:
#!/usr/bin/perl -w use strict; sub do_this { print "doing this!\n" } sub do_that { print "doing that!\n" } my $code = get_coderef('do_this'); $code->(); $code = get_coderef('do_that'); $code->(); $code = get_coderef('do_nothing'); if (defined($code)) { $code->(); } else { print "Not defined!\n"; }

In reply to Re: How to use a scalar variable to call a subroutine? by chromatic
in thread How to use a scalar variable to call a subroutine? by apprentice

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.