Using module whith name stored in variable

Using module whith name stored in variable

am 07.04.2008 09:50:10 von Alien

Hello all!
Can anybody tell how can I use modele which name stored in variable?
For example, I have this code:

########################################
package MyModule;

use strict;
use Exporter;
use vars qw(@ISA @EXPORT $DEBUG);

@ISA = qw/Exporter/;
@EXPORT = qw(foo);

sub foo($)
{
my $arg = shift;
print "MyModule foo: my arg: '$arg'\n";
return undef;
}

1;
########################################


Here are the code of main programm

########################################
#!/usr/local/bin/perl

use strict;
my $module = 'MyModule.pm';
require $module; # load module

my $arg = 'MyArg';

# I want call procedure by full name. How I can do this?
my $mname = 'MyModule';
$mname::foo($arg); # This doesn't work!!!

exit 0;
########################################

Thanks for help

Re: Using module whith name stored in variable

am 07.04.2008 10:49:45 von Gunnar Hjalmarsson

Alien wrote:
> Can anybody tell how can I use modele which name stored in variable?



> # I want call procedure by full name. How I can do this?
> my $mname = 'MyModule';
> $mname::foo($arg); # This doesn't work!!!

One way is via a reference to the sub:

my $subref = \&{$mname.'::foo'};
$subref->($arg);

Also, you should read the FAQ entry

perldoc -q "variable name"

--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl

Re: Using module whith name stored in variable

am 07.04.2008 12:31:47 von Alien

>
> One way is via a reference to the sub:
>
> =A0 =A0 =A0my $subref =3D \&{$mname.'::foo'};
> =A0 =A0 =A0$subref->($arg);
>
> Also, you should read the FAQ entry
>
> =A0 =A0 =A0perldoc -q "variable name"
>
> --
> Gunnar Hjalmarsson
> Email:http://www.gunnar.cc/cgi-bin/contact.pl

That's great!
Thank you very mutch! I didn't know where to search the answer. How
easy it was!