my $t= XML::Twig->new( elt_class => 'my_elt_class', p => sub { $_->cut # an XML::Twig::Elt method ->my_process; # a my_elt_class method } ); package my_elt_class; BEGIN { @my_elt_class::ISA=('XML::Twig::Elt'); } # to inherit from XML::Twig::Elt sub my_process { my $elt= shift; # stuff here } #### # in XML::Twig, every time it needs to create an element $self->{elt_class} || 'XML::Twig::Elt'; my $element= $elt_class->new; #### #!/usr/bin/perl -w use strict; foreach my $elt_class ( '', 'my_elt1', 'my_elt2', 'my_elt3') { warn "testing $elt_class"; my $t= XML::Twig->new( elt_class => $elt_class); my $e= $t->add_elt; $e->print; } package XML::Twig; sub new { my $class= shift; return bless { @_ }; } sub add_elt { my $self= shift; $self->{elt} ||= []; # this is where it all happens my $elt_class= $self->{elt_class} || 'XML::Twig::Elt'; my $e= $elt_class->new; push @{$self->{elt}}, $e; return $e; } package XML::Twig::Elt; sub new { my $class= shift; warn " new elt $class in XML::Twig::Elt\n"; return bless { @_ }, $class; } sub print { print " printing from XML::Twig::Elt\n"; } # redefines new and print package my_elt1; # the BEGIN is needed or @my_elt1::ISA would not actually be initialized BEGIN { @my_elt1::ISA= qw(XML::Twig::Elt); } sub new { my $class= shift; warn " new my_elt1 in my_elt1\n"; return bless { @_ }, $class; } sub print { print " printing from my_elt1\n"; } # redefines print (new is inherited) package my_elt2; BEGIN { @my_elt2::ISA= qw(XML::Twig::Elt); } sub print { print " printing from my_elt2\n"; } # does not redefine anything, both new and print are inherited package my_elt3; BEGIN { @my_elt3::ISA= qw(XML::Twig::Elt); }