Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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

by LanX (Saint)
on Apr 14, 2019 at 14:16 UTC ( [id://1232552]=note: print w/replies, xml ) Need Help??


in reply to Function name in a variable, can't recall the concept

If you want to appease your supervisor use UNIVERSAL::can()

my $func_name = ( $someCondition ? 'foo' : 'bar' ); my $func_ref = __PACKAGE__->can($func_name); # or other pac +kage $func_ref->($arg1, $arg2);

I'm sure there is a similar method like can() in Python too.

> What is the name of the idiom

When talking to non-Perlers I'd use the general term "introspection"

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

Update:

->can is also strict and more stable, since you can easily catch missing subs.

It won't work with AUTOLOAD though

Replies are listed 'Best First'.
Re^2: Function name in a variable, can't recall the concept (introspection with ->can )
by ikegami (Patriarch) on Apr 15, 2019 at 01:00 UTC

    No, you shouldn't. can performs a method lookup, not a sub lookup.

    As for not working with AUTOLOAD, that would indicate a bug in the class using AUTOLOAD. It should override can to provide a meaningful result.

      > No, you shouldn't. can performs a method lookup, not a sub lookup.

      ->can does a sub lookup if @ISA is empty, and the content of @ISA is introspectable too.

      And using a package for a module and a class is a pretty dubious concept.

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

        If I understand correctly, you're saying it's ok to use can if you make sure to check that @ISA is empty first?

        1) You didn't do that, so I guess you're saying your code is wrong too?

        2) You'd need to use an alternative approach when @ISA isn't empty. Why not use that all the time?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-03-29 01:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found