Skip to Content
Intermediate Perl
book

Intermediate Perl

by Randal L. Schwartz, brian d foy, Tom Phoenix
March 2006
Intermediate to advanced
278 pages
6h 49m
English
O'Reilly Media, Inc.
Content preview from Intermediate Perl

Chapter 12. Objects with Data

Using the simple syntax introduced in Chapter 11, we have class methods, (multiple) inheritance, overriding, and extending. We’ve been able to factor out common code and provide a way to reuse implementations with variations. This is at the core of what objects provide, but objects also provide instance data, which we haven’t even begun to cover.

A Horse Is a Horse, of Course of Course—or Is It?

Let’s look at the code used in Chapter 11 for the Animal classes and Horse classes:

{ package Animal;
  sub speak {
    my $class = shift;
    print "a $class goes ", $class->sound, "!\n"
  }
}
{ package Horse;
  @ISA = qw(Animal);
  sub sound { 'neigh' }
}

This lets us invoke Horse->speak to ripple upward to Animal::speak, calling back to Horse::sound to get the specific sound, and the output of:

a Horse goes neigh!

But all Horse objects would have to be absolutely identical. If we add a method, all horses automatically share it. That’s great for making horses identical, but how do we capture the properties of an individual horse? For example, suppose we want to give our horse a name. There’s got to be a way to keep its name separate from those of other horses.

We can do so by establishing an instance. An instance is generally created by a class, much like a car is created by a car factory. An instance will have associated properties, called instance variables (or member variables, if you come from a C++ or Java background). An instance has a unique identity (like the serial number ...

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

Perl Debugged

Perl Debugged

Peter Scott, Ed Wright
Think Perl 6

Think Perl 6

Laurent Rosenfeld, Allen B. Downey
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Pro Perl

Pro Perl

Peter Wainwright

Publisher Resources

ISBN: 0596102062Supplemental ContentErrata Page