Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^8: Function name in a variable, can't recall the concept (introspection with ->can )

by Veltro (Hermit)
on Apr 19, 2019 at 13:51 UTC ( [id://1232803]=note: print w/replies, xml ) Need Help??


in reply to Re^7: Function name in a variable, can't recall the concept (introspection with ->can )
in thread Function name in a variable, can't recall the concept

He probably means something hypothetical...

I was actually thinking about this seriously, and I would likely do something as:

sub get_sub_by_name { my ($pkg, $name) = @_ ; no strict 'refs' ; if ( exists ${$pkg . '::'}{$name} ) { if ( ref ${$pkg . '::'}{$name} eq 'CODE' ) { return *{$pkg . '::' . $name} ; } } ; }

Maybe it can be written more pretty, and I don't know if any odd-cases are trapped (e.g. what about __ANON__)

edit: Comes to think of it, maybe the line 'exists' is not even needed?

  • Comment on Re^8: Function name in a variable, can't recall the concept (introspection with ->can )
  • Download Code

Replies are listed 'Best First'.
Re^9: Function name in a variable, can't recall the concept (introspection with ->can )
by LanX (Saint) on Apr 19, 2019 at 15:23 UTC
    I'm afraid your hypothetical code for his hypothetical function is ignoring how typeglobs work.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

      Oh yeah, haha, what have I been smoking!

      I'll probably stick with this then:

      sub get_sub_by_name { my ($pkg, $name) = @_ ; no strict 'refs' ; if ( defined &{$pkg . '::'. $name} ) { return \&{$pkg . '::'. $name} ; } }

        \&$name works even under strict refs. No need to turn it off.

        You need to return something (undef?) in the else case.

        > I been smoking!

        something very strong it's still broken.

        update

        I was wrong, it works almost as well as ->can for non-class modules.

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1232803]
help
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-19 13:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found