Perl for Newbies - Part 3 - Modules and ObjectsObjects in PerlMaking Your Own ObjectsObject Inheritance

4.3.3. Object Inheritance

Now, let's suppose we would like to create a class similar to Foo, that's also keeps track of the number of times its name was assigned. While we can write a completely different object, we can inherit from Foo and use what we already have in place.

Here's a class derived from Foo that has a method assign_name_ext that keeps track of the number of times it was called, and a method get_num_times_assigned that retrieves this number:

package Bar;

use strict;
use warnings;

# @ISA is not lexically scoped so it has to be declared with
# use vars.
# qw(My Constant String) is equivalent to split(/\s+/, "My Constant String")
use vars qw(@ISA);

# We use Foo during our inheritance so we should load it.
use Foo;

# This command actually inherits Foo.

sub assign_name_ext
    my $self = shift;

    my $name = shift;

    # Call the method of the base class
    my $ret = $self->assign_name($name);
    if (! $ret)

    return $ret;

sub get_num_times_assigned
    my $self = shift;

        (exists($self->{'num_times'}) ?
            $self->{'num_times'} :


Written by Shlomi Fish