Learning Perl Objects, References & ModulesLearning Perl Objects, References & ModulesSearch this book

8.2. Introducing the Method Invocation Arrow

A class is a group of things with similar behaviors and traits. For now, let's say that Class->method invokes subroutine method in package Class. That's not completely accurate, but you'll catch on one step at a time. Let's use it like so:

sub Cow::speak {
  print "a Cow goes moooo!\n";
}
sub Horse::speak {
  print "a Horse goes neigh!\n";
}
sub Sheep::speak {
  print "a Sheep goes baaaah!\n";
}

Cow->speak;
Horse->speak;
Sheep->speak;

And once again, this results in:

a Cow goes moooo!
a Horse goes neigh!
a Sheep goes baaaah!

That's not fun yet. You've got the same number of characters, all constant, no variables. However, the parts are separable now:

my $beast = "Cow";
$beast->speak;                # invokes Cow->speak

Ahh! Now that the package name is separated from the subroutine name, you can use a variable package name. This time, you've got something that works even when use strict 'refs' is enabled.

Take the arrow invocation and put it back in the barnyard example:

sub Cow::speak {
  print "a Cow goes moooo!\n";
}
sub Horse::speak {
  print "a Horse goes neigh!\n";
}
sub Sheep::speak {
  print "a Sheep goes baaaah!\n";
}

my @pasture = qw(Cow Cow Horse Sheep Sheep);
foreach my $beast (@pasture) {
  $beast->speak;
}

There! Now all the animals are talking, and safely at that, without the use of symbolic coderefs.

But look at all that common code. Each speak routine has a similar structure: a print operator and a string that contains common text, except for two words. One of OOP's core features minimizes common code: if you write it only once, you'll save time. If you test and debug it only once, you'll save more time.

Now that you've learned more about what the method invocation arrow actually does, we've got an easier way to do the same thing.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.