9.2 Invoking an Instance Method

The method arrow can be used on instances, as well as names of packages (classes). Let's get the sound that $tv_horse makes:

my $noise = $tv_horse->sound;

To invoke sound, Perl first notes that $tv_horse is a blessed reference, and thus an instance. Perl then constructs an argument list, similar to the way an argument list was constructed when you used the method arrow with a class name. In this case, it'll be just ($tv_horse). (Later you'll see that arguments will take their place following the instance variable, just as with classes.)

Now for the fun part: Perl takes the class in which the instance was blessed, in this case Horse, and uses it to locate the subroutine to invoke the method, as if you had said Horse->sound instead of $tv_horse->sound. The purpose of the original blessing is to associate a class with that reference to allow the proper method (subroutine) to be found.

In this case, Horse::sound is found directly (without using inheritance), yielding the final subroutine invocation:


Note that the first parameter here is still the instance, not the name of the class as before. neigh is the return value, which ends up as the earlier $noise variable.

If Horse::sound had not been found, you'd wander up the @Horse::ISA list to try to find the method in one of the superclasses, just as for a class method. The only difference between a class method and an instance method is whether the first parameter is an instance (a blessed reference) or a class name (a string).[4]

[4] This is perhaps different from other OOP languages with which you may be familiar.