引用Perl中带有字符串的模块

Man*_*ken 1 perl perl-module

我有一个带有模块名称的字符串,需要使用它来实例化一个对象.这怎么做得最好?我正在寻找类似的东西

foo.pl

#!/usr/bin/perl
use strict;
use Bar;

my $module = "Bar";
my $obj = {$module}->new(); # does not work

$obj->fun (123);
Run Code Online (Sandbox Code Playgroud)

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";
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*man 5

你太复杂了. $module->new单独工作没有{braces}:

$ perl -MXML::Simple -E 'use strict; my $foo = "XML::Simple"; my $obj = $foo->new; say $obj'
XML::Simple=HASH(0x9d024d8)
Run Code Online (Sandbox Code Playgroud)