Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Module Function By Reference

I am looking at building a dispatch table for calling a number of Perl modules that I wrote.

As an example, if I have a package called Hello.pm with a simple function hello() in it, I would like to get a code reference to this function.

The following does not work:

my $code_ref=\&Hello->hello();
$code_ref->();

But if the function hello is exported from the package, then the following works:

my code_ref=\&hello;
code_ref->();

Does anyone know the correct syntax for the first case? Or is this simply not possible?

In the end, I would like to populate a hash table with all my code references.

##### Thanks for All Answers

The correct invocation as pointed out by several answers is:

my $code_ref=\&Hello::hello;
$code_ref->();

I have some 10 modules in 10 different files that I would like to load in a dispatch table. This makes it easier for me to have the configuration loaded as data, and separate from code. This allows me to load additional modules in a testbench without modifying my code-simply modify the configuration file. Mark Dominus, author of Higher Order Perl, has some nice examples on this.

like image 484
sammy Avatar asked Dec 01 '22 22:12

sammy


1 Answers

If you want to refer to the hello sub in the Hello module, then call it, use:

my $code_ref = \&Hello::hello;
$code_ref->();

If you want to call a method named "hello" in Hello, you can do it like this:

my $method = "hello";
Hello->$method();
like image 197
Charles Engelke Avatar answered Dec 04 '22 22:12

Charles Engelke