Ana Saiz García am Montag, 12. Februar 2007 22:26:
> Hello

Hello Ana

> 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?
>
> Thanks in advance, and if I haven't been able to explain it well, please
> ask me :o)

Hm, one way would be to use subroutine typeglobs. In the following 
demonstration code, all modules are included into the main script for 
shortness.

You can find information in
perldoc perldata 
("Typeglobs and Filehandles") - don't know of other resources at the moment.

#!/usr/bin/perl

# don't forget:
#
use strict;
use warnings;

package A;
sub hello { print "hello from A\n" }

package B;
sub hello { print "hello from B\n" }

# implicit namespace in main scripts; 
# only needed here because of the package declarations above
#
package main; 
             
# can be got via cmdline or whatever source
# 
my $pkg='A'; 

# we get the wanted sub via a subroutine type glob at runtime...
#
my $sub=\&{$pkg.'::hello'}; 

# ...and call it indirectly
#
$sub->();

__END__

Hope this helps!

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to