Skip to Content
Programming Perl, 4th Edition
book

Programming Perl, 4th Edition

by Tom Christiansen, brian d foy, Larry Wall, Jon Orwant
February 2012
Intermediate to advanced
1184 pages
37h 17m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 4th Edition

Inheritable Constructors

Like all methods, a constructor is just a subroutine, but we don’t call it as a subroutine. We always invoke it as a method—a class method, in this particular case, because the invocant is a package name. Method invocations differ from regular subroutine calls in two ways. First, they get the extra argument we discussed earlier. Second, they obey inheritance, allowing one class to use another’s methods.

We’ll describe the underlying mechanics of inheritance more rigorously in the next section, but, for now, some simple examples of its effects should help you design your constructors. For instance, suppose we have a Spider class that inherits methods from the Critter class. In particular, suppose the Spider class doesn’t have its own spawn method. The correspondences shown in Table 12-1 apply:

Table 12-1. Mapping methods to subroutines

Method CallResulting Subroutine Call
Critter–>spawn()Critter::spawn("Critter")
Spider–>spawn()Critter::spawn("Spider")

The subroutine called is the same in both cases, but the argument differs. Note that our spawn constructor above completely ignored its argument, which means our Spider object was incorrectly blessed into class Critter. A better constructor would provide the package name (passed in as the first argument) to bless:

sub spawn {
    my $class =  shift;       # Store the package name
    my $self  =  { };
    bless($self, $class);     # Bless the reference into that package
    return $self;
}

Now you could use the same subroutine for both these cases: ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Perl, 3rd Edition

Programming Perl, 3rd Edition

Larry Wall, Tom Christiansen, Jon Orwant
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes
Learning Perl, 8th Edition

Learning Perl, 8th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix

Publisher Resources

ISBN: 9781449321451Supplemental ContentErrata Page