This sounds like basic inheritance.
package Parent;
sub new {
my ($class, @args) = @_;
bless [ @args ], $class;
}
package Child;
@ISA = 'Parent';
Calling Child->new will call Parent's new() method, but $class will be 'Child', not 'Parent'.
The "trick" is using the first argument to the class method as the class name, not hardcoding the class name into your code.
| [reply] [d/l] |
Have a look at perltoot and into OO Tutorials in the Tutorials section of the monastery.
What you need is a constructor that uses the bless function together with the class name.
You can obtain an object's class name using the ref-function.
Cheers, Sören
| [reply] |
The ref function returns the class name of an object, so you can bless a reference into a class with it,
my $object = Foo->new;
my $fake = bless {}, ref $object;
my $real = (ref $object)->new;
There is no assurance that Foo's instance methods will work with $fake. Know what your classes are like before you do this.
You can bless a reference into any namespace you like - it doesn't even have to exist in the symbol table.
| [reply] [d/l] |
sub factory {
my $class_name = shift;
my @args = @_;
return $class_name->new( @args );
}
my $foo = factory( 'Class1', $arg1 );
my $bar = factory( 'Class2', $arg2 );
Though, frankly, since you can use a variable name as I am doing in the factory() function, you can just avoid it altogether.
My criteria for good software:
- Does it work?
- Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
| [reply] [d/l] |