#!perl # in a file: BaseObj.pm use strict; use warnings; =head1 NAME BaseObj - Base Class for the home and region. =head1 SYNOPSIS use BaseObj; =head1 DESCRIPTION BaseObj keeps track of the home and region. =head1 USAGE my $base = BaseObj->new; # show default home: San Diego and region: West Coast print $base->go; $base->home("New York"); $base->region("East Coast"); print $base->go; =head1 BUGS none. =head1 AUTHOR David Scott =head1 METHODS Methods follow for the BaseObj class: =over 4 =cut package BaseObj; use fields qw/home region/; =item my $base = BaseObj->new; This is an object Constructor. Create a base object which defaults to the home of California and the region, West Coast. =cut sub new { my ($self) = shift; unless ( ref($self) ) { $self = fields::new($self); } $self->{home} = "California"; $self->{region} = "West Coast"; return $self; } =item $base->go; Return a string which says where I'm going. =cut sub go { my ($self) = @_; return "Going home to " . $self->{home} . " in the " . $self->{region} . "\n"; } use Carp; our $AUTOLOAD; =item AUTOLOAD $base->home; and $base->home("New York"); ... Get or set any BaseObj or inherited field by default. The field must exist or it will generate an error. =cut 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}; } } =item $base->DESTROY; Explicit destroy required because of AUTOLOAD, by default it does nothing. Overload for any Object cleanup at deconstruction of objects. =cut sub DESTROY { } =back =cut 1; # enables Perl to know it loaded properly