#!perl # in a file: BaseObj.pm use strict; use warnings; package BaseObj; use fields qw/home region/; use Carp; our $AUTOLOAD; # new - construct a BaseObj object sub new { my ($self) = shift; unless ( ref($self) ) { $self = fields::new($self); } $self->{home} = "California"; $self->{region} = "West Coast"; return $self; } # go - tells where I'm going sub go { my ($self) = @_; return "Going home to " . $self->{home} . " in the " . $self->{region} . "\n"; } # Get or set any BaseObj field by default. sub AUTOLOAD { my $self = shift; my $type = ref($self) or croak "$self is not an object"; my $name = $AUTOLOAD; $name =~ s/.*://; # strip fully-qualified portion croak "Can't access `$name' field in class $type" unless (exists $self->{$name}); if (@_) { return $self->{$name} = shift; } else { return $self->{$name}; } } # explicit destroy required because of AUTOLOAD sub DESTROY { } 1; # enables Perl to know it loaded properly