Hi Ana,

On 2007/02/12, at 21:26, Ana Saiz García wrote:

Hello

First of all, I apologize if this is not the right list to ask my question, but as I am a perl beginner, I think it is the most suitable list for me :o)

So here goes my question:

I have a main program which will call a subroutine, say "S", belonging to another module. The question is that there could be several modules that contain a subroutine also named "S", which basically will return equivalent
values to the main program.

My problem is that I don't want to harcode the name of those modules (for example using an "if"), because I don't know a priori how many there will be or which will be needed to call at any moment. The idea is that there will be a file in which the main program could read which module is necessary in
each moment, and so call it.

So the question is: Is there any way to call a subroutine without explicitly
writing his name?


You can use the UNIVERSAL's can() method. Assuming you have a module called "M";

<code>
package M;

sub some_function {
        print "some_function()", "\n";
}

package main;

my $function_name = "some_function";
if (my $coderef = M->can($function_name)) {
        $coderef->();
}
</code>

Good luck!

--
Igor Sutton Lopes <[EMAIL PROTECTED]>



Attachment: PGP.sig
Description: This is a digitally signed message part

Reply via email to