in reply to Dynamically setting up inheritence at runtime

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.

Replies are listed 'Best First'.
Re^2: Dynamically setting up inheritence at runtime
by hangon (Deacon) on Jan 26, 2009 at 21:17 UTC

    Thanks ikegami this is what I'm looking for. Now that I understand a little better I'll take a look at module::pluggable.