Reputation: 119
I have a string with a module name and need to use this to instantiate an object. How is this best done? I am looking for something like
foo.pl
#!/usr/bin/perl
use strict;
use Bar;
my $module = "Bar";
my $obj = {$module}->new(); # does not work
$obj->fun (123);
Bar.pm
package Bar;
use strict;
sub new
{
my $self = {};
return bless $self;
}
sub fun
{
my ($self, $arg);
print "obj $self got arg $arg\n";
}
Upvotes: 1
Views: 471
Reputation: 2150
Besides the provided notes about unnecessary braces, you could be interested in Class::MOP or Class::Load (for more recent code), especially the load_class()
subroutine, for a more dynamic loading of modules/classes.
Upvotes: 0
Reputation: 46187
You're overcomplicating. $module->new
works just fine on its own with no {braces}:
$ perl -MXML::Simple -E 'use strict; my $foo = "XML::Simple"; my $obj = $foo->new; say $obj'
XML::Simple=HASH(0x9d024d8)
Upvotes: 5
Reputation: 884
You have to use the Perl function eval
.
You also have to use ref
to get the name of a perl Object.
But first of all your foo method isn't taking the arguments, here is a corrected version :
package Bar;
use strict;
sub new
{
my $self = {};
return bless $self;
}
sub fun
{
my ($self, $arg) = @_;
print "obj ".ref($self)." got arg $arg\n";
}
1;
Here is the test script :
#!/usr/bin/perl
use strict;
use Bar;
my $module = "Bar";
my $obj = eval {$module->new()};
$obj->fun (123);
Output : obj Bar got arg 123
Upvotes: -1