Section 11.2. Introducing the Method Invocation Arrow


11.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. A method is the object-oriented version of the subroutine, so we'll say "method" from now on.[*] That's not completely accurate, but we'll go on one step at a time. Let's use it like so:

[*] In Perl, there really isn't a difference between a subroutine and a method. They both get an argument list in @_, and we have to make sure we do the right thing.

 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. We'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, we can use a variable package name. This time, we've got something that works even when we enable use strict 'refs'.

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 method has a similar structure: a print operator and a string that contains common text, except for two words. One of OOP's core principles is to minimize common code: if we write it only once, we'll save time. If we test and debug it only once, we'll save more time.

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




Intermediate Perl
Intermediate Perl
ISBN: 0596102062
EAN: 2147483647
Year: N/A
Pages: 238

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net