Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Your question suggests a logical confusion. One can't store a subroutine in a scalar variable. You can store a reference to a subroutine in a scalar variable, or you can, as in your code, store the name of a subroutine in a scalar variable.

In the former case, the answer to your question is easy:

my $coderef = \&some_sub; # $coderef contains a reference to &some_su +b my $results = $coderef->();

In the latter case, you can either use eval:

my $subname = 'some_sub'; my $results = eval "$subname()"; die $@ if $@;
or you can treat it as a symbolic ref:
my $results = do { no strict 'refs'; $subname->() };

use strict; use warnings; sub some_sub { print "Hello world!\n"; return 42; } my $coderef = \&some_sub; my $subname = 'some_sub'; print $coderef->(), "\n"; print eval "$subname()", "\n"; die $@ if $@; print do { no strict 'refs'; $subname->() }, "\n"; __END__ Hello world! 42 Hello world! 42 Hello world! 42

But storing names of subroutines in variables should be a red flag to alert you that you are probably not thinking about the problem in the right way.

the lowliest monk


In reply to Re: Calling a subroutine from a scalar by tlm
in thread Calling a subroutine from a scalar by metalgear119

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2024-04-16 17:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found