Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Elegant way to call a method

by siberia-man (Friar)
on Dec 23, 2017 at 10:10 UTC ( [id://1206099]=perlquestion: print w/replies, xml ) Need Help??

siberia-man has asked for the wisdom of the Perl Monks concerning the following question:

This question has been discussed by someone already: How can I elegantly call a Perl subroutine whose name is held in a variable?. But it doesn't answer the question completely. Actually I have the following code. It works but looks a bit ugly:
if ( defined &{ "some::cool::${module}::method" } ) { &{ \&{ "some::cool::${module}::method" } }(some arguments); } else { ... }
I can check the method availability as below but don't know how to proceed further in term of my question:
if ( "some::cool::${module}"->can("method") ) { ???

Replies are listed 'Best First'.
Re: Elegant way to call a method
by Corion (Patriarch) on Dec 23, 2017 at 10:44 UTC

    The return value of can is a function reference:

    if ( my $handler = "some::cool::${module}"->can("method") ) { $handler->( ... some arguments ... ) } else { ... }
      Thank you. I was in one step behind this solution.
Re: Elegant way to call a method
by eyepopslikeamosquito (Archbishop) on Dec 23, 2017 at 10:57 UTC
      Interesting discussion. I will try to keep this in mind on the case if something similar happen in my work.
Re: Elegant way to call a method
by Anonymous Monk on Dec 26, 2017 at 13:50 UTC
    Just as you do not want a variable to contain the arbitrary name of a variable that you reference, you do not want a variable to contain the arbitrary name of a function that you call. Dispatch-tables, by any other name, are a fine solution ... so are if..elsif blocks. Throw an exception at a well-defined point if you are given a name that you are not somehow explicitly-prepared to recognize, because this is the only way that you will find that bug. Another technique that I like to use is to specify that the variable must be the name of an object of a specified class or parent-class, which contains a method that I will call. The invoking routine verifies that the object exists, and that it is of the proper class, and wraps the method-call in an exception handler. (This strategy provides context, contained in the object-instance.) You can do this sort of thing in many programming languages and it works everywhere.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1206099]
Approved by holli
Front-paged by haukex
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (4)
As of 2024-04-18 21:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found