Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^2: How to map function name to coderef?

by Anonymous Monk
on Jan 07, 2012 at 00:15 UTC ( #946686=note: print w/ replies, xml ) Need Help??


in reply to Re: How to map function name to coderef?
in thread How to map function name to coderef?

Is there a way to do this with strict enabled?


Comment on Re^2: How to map function name to coderef?
Download Code
Re^3: How to map function name to coderef?
by GrandFather (Sage) on Jan 07, 2012 at 00:36 UTC

    You can use can to return a coderef:

    use strict; use warnings; my $doFoo = main->can ('foo'); print $doFoo ? $doFoo->() : "Can't foo\n"; sub foo { return 1; }

    Prints:

    1
    True laziness is hard work
      can searches the inheritance tree. It should be used for methods, not functions.

        And yet can works, and as there is no @main::ISA, and you shouldn't pollute UNIVERSAL,  main->can( $foo ) is perfectly legit

Re^3: How to map function name to coderef?
by ikegami (Pope) on Jan 07, 2012 at 00:39 UTC

    Yes, there are ways of fooling strict. It's simpler and clearer to just turn it off in the code in question.

    my $func_name = 'f'; my $cr = do { no strict 'refs'; \&$func_name }; say $cr->();

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://946686]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2015-07-02 01:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (25 votes), past polls