sub foo
{
my $self = shift;
$self->{foo} = shift if @_;
return $self->{foo};
}
####
for my $field (qw(name race aliases)) {
my $slot = __PACKAGE__ . "::$field";
no strict "refs"; # So symbolic ref to typeglob works
*$field = sub {
my $self = shift;
$self->{$slot} = shift if @_;
return $self->{$slot};
};
}
####
#!/usr/bin/perl
use strict;
use warnings;
package Foo;
sub new
{
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = { };
bless $self, $class;
$self->{baz} = 1;
$self->{bah} = 2;
return $self;
}
sub baz
{
die "baz() not overriden\n";
}
sub bah
{
die "bah() not overriden\n";
}
package Bar;
our @ISA = qw(Foo);
for my $field (qw(baz bah)) {
my $slot = __PACKAGE__ . "::$field";
no strict 'refs'; # Need symbolic refs to typeglob
*$field = sub {
my $self = shift;
$self->{$slot} = shift if @_;
return $self->{$slot};
};
}
package main;
my $obj = Bar->new();
print "Baz: ", $obj->baz, "\n";
print "Bah: ", $obj->bah, "\n";
####
Baz: 1
Bah: 2
####
#!/usr/bin/perl
use strict;
use warnings;
package Foo;
sub new
{
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = { };
bless $self, $class;
$self->{baz} = 1;
$self->{bah} = 2;
return $self;
}
sub baz
{
die "baz() not overriden\n";
}
sub bah
{
die "bah() not overriden\n";
}
package Bar;
our @ISA = qw(Foo);
my @DYNAMIC_METHODS = qw(faz);
sub make_methods
{
for my $field (@DYNAMIC_METHODS) {
my $slot = __PACKAGE__ . "::$field";
no strict 'refs';
*$field = sub {
print "Called faz\n";
};
}
}
sub destroy_methods
{
for my $field (@DYNAMIC_METHODS) {
my $slot = __PACKAGE__ . "::$field";
no strict 'refs';
undef *$field;
}
}
for my $field (qw(baz bah)) {
my $slot = __PACKAGE__ . "::$field";
no strict 'refs'; # Need symbolic refs to typeglob
*$field = sub {
my $self = shift;
$self->{$slot} = shift if @_;
return $self->{$slot};
};
}
package main;
my $obj = Bar->new();
print "Baz: ", $obj->baz, "\n";
print "Bah: ", $obj->bah, "\n";
$obj->make_methods();
$obj->faz();
$obj->destroy_methods();
$obj->faz();