Best way to pass module creator reference

D

Drago

I have a module which I would like to be able to create instances of a
class it knows nothing about. Is there a neat way short of an anonymous
subroutine, like this example:

use Foo;
use Bar;
# this works, but seems overly verbose
Bar->new(sub { Foo->new(@_) } );

I note that

$c = \&Foo;
print ref($c); # says CODE

but within my module, one cannot then say

$c->new(...);

So I am not sure what \&Foo is giving me (i.e. a code reference to
what?). So is there a better way than the way I did it in the first example?
 
A

Andrew Tkachenko

use Foo;

sub make_obj {
my $class = shift;
return $class->new(@_);
}

my $foo = make_obj("Foo", arg1 =>12, arg2 =>13)'

Probably this is what you looking for.

Regards, Andrew

Drago wrote on 12 ÐоÑбрь 2004 01:04:
I have a module which I would like to be able to create instances of a
class it knows nothing about. Is there a neat way short of an anonymous
subroutine, like this example:

use Foo;
use Bar;
# this works, but seems overly verbose
Bar->new(sub { Foo->new(@_) } );

I note that

$c = \&Foo;
print ref($c); # says CODE

but within my module, one cannot then say

$c->new(...);

So I am not sure what \&Foo is giving me (i.e. a code reference to
what?). So is there a better way than the way I did it in the first
example?
 
A

Andres Monroy-Hernandez

Drago said:
I have a module which I would like to be able to create instances of a
class it knows nothing about. Is there a neat way short of an anonymous
subroutine, like this example:

use Foo;
use Bar;
# this works, but seems overly verbose
Bar->new(sub { Foo->new(@_) } );

I note that

$c = \&Foo;
print ref($c); # says CODE

but within my module, one cannot then say

$c->new(...);

So I am not sure what \&Foo is giving me (i.e. a code reference to
what?). So is there a better way than the way I did it in the first
example?

I am not sure how clean this is, but you could pass a string with the
name of the class that you want to instantiate.

use strict;
use warnings;
my $foo = Foo->new('Bar');
print ref($foo), ",", ref($foo->{object}), "\n";

package Foo;
sub new {
my ($class, $param) = @_;
my $this;
eval ( "\$this->{object} = $param->new('test');");
return bless($this, $class);
}

package Bar;
sub new {
my $class = shift;
my $this = { value => shift };
return bless($this, $class);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top