Smartelf
Smartelf

Reputation: 879

perl: initializing an object from a string

I have a library of objects in perl all having the same function_calls. I am looking for how to create an approriate object from the library from a string.

my $object_name='myObject';#would actually be a hash lookup from user input with appropriate error checks
my $string = "return ${object_name}->new(\@params);";
my $object = eval $string;
$object->some_function();

Now I am having a problem, it works for some objects and doesn't for others? Is there a more reliable way of doing this. I have tried printing the string out before eval and it appears to be correct with the correct class name, also every object takes the same parameter, any Ideas, thanks.

Upvotes: 1

Views: 2226

Answers (1)

Eric Strom
Eric Strom

Reputation: 40152

The eval is not necessary since a string can be used as a package name, so the lines:

my $object_name = 'myObject';

my $object = $object_name->new(@params);

Will do what you want. If you want to make sure that myObject is actually a valid package name you could do:

my $object_name = 'myObject';

unless ($object_name->can('new')) {
    die "bad object name: $object_name";
}
my $object = $object_name->new(@params);

Upvotes: 10

Related Questions