Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl create class object by using variable as class name

Tags:

perl

Is this possible using Perl:

my @array = ($class1,$class2,$class3);

foreach my $c (@array)
{
    my $temp = $c->new();
    $temp->run($var1,$var2);
}

The idea behind this is that the array will always contain different class names. I would then like to create an object of that class and run a method from it. Each class is somewhat similar but contains its own logic in the run method?

If this is not possible, is there a different way i could do this? Is this bad programming?

like image 397
Ivan Bacher Avatar asked Apr 15 '26 09:04

Ivan Bacher


1 Answers

You need to make sure that the run-Method is always accessible:

my @array = ($class1,$class2,$class3);

foreach my $class (@array) {
    my $temp = $class->new();
    if ($temp->can('run') {
        $temp->run($var1,$var2);
    } else {
        ...
    }
}