Invoking an Instance Method






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 we used the method arrow with a class name. In this case, it'll be just ($tv_horse). (Later we'll show 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 and invoke the method, as if we 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 Perl to find the proper method.

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

Horse::sound($tv_horse)

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 Perl did not find Horse::sound, it would walk 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).[*]

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



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows