Have a function create an object of the appropriate type.
use strict; use warnings; my $ob1 = My::File::Handler->new_handler('work.txt'); my $ob2 = My::File::Handler->new_handler('work.doc'); $ob1->write(); $ob2->write(); BEGIN { package My::File::Handler; sub new_handler { my ($class, $fn) = @_; my $ext = ...; # built from $fn my $pkg = ...; # built from $ext return $pkg->new($fn); } sub new{ my ($class, $fn) = @_; return bless {}, $class; } sub write{ my $self = shift; print $self->read; } sub read{ die "Abstract"; } } BEGIN { package My::File::Handler::txt; our @ISA = 'My::File::Handler'; sub read{ return __PACKAGE__; } } BEGIN { package My::File::Handler::doc; our @ISA = 'My::File::Handler'; sub read{ return __PACKAGE__; } }
new_handler should probably be a method of another class.
I'd probably use Module::Pluggable to load the appropriate handler.
In reply to Re: Dynamically setting up inheritence at runtime
by ikegami
in thread Dynamically setting up inheritence at runtime
by hangon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |