There are three ways that I know of to call a sub as a variable. You can store a pointer to an anonymous function in a variable and call that, but I dont think this is what you are looking for. You can also store the proper function name in a variable can call it by just prepending a '&' on the front like
$var = 'funcname'; &$var(); sub funcname { print "Hello\n" }
But this will not work if you are using 'strict', so here are the three ways you can do it that will work with strict.
use strict; # # create an anonymous function # my $func = sub { print "Sub Anonymous\n" }; # # create named sub # sub funcname { print "Sub funcname\n" } # # call anonymous subroutine # &$func(); my $mysub = 'funcname'; # # call subroutine but only with no strict references # no strict 'refs'; &$mysub(); use strict; # # or call with eval statement # eval('&'.$mysub.'()'); # # catch error from eval statement # if( $@ ) { warn($@); }
The first one is just an anonymous subroutine, and the next two are calling a name subroutine referenced in a variable. By turning off 'strict refs' you run the risk of getting a crtitical run time error if there is no function named in $mysub. So it is probably better to use the eval and catch the error. That will prevent the program from critically failing if the function does not exist.

In reply to Re: using variables as functions by perlmonkey
in thread using variables as functions by Anonymous Monk

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.