In terms of Perl OO, what exactly does -> do?
For example I make a call main:
$result = a::b->mymethod( );
In the package where I define mymethod(), I use the following:
my( $class ) = @_;
In main, I clearly don’t pass any arguments to mymethod(), so where is the $class argument coming from? Has anyone got a good explanation for this or a document that explains this?
The “Method Invocation” section of the perlobj documentation explains. The added emphasis is mine.
Method Invocation
For various historical and other reasons, Perl offers two equivalent ways to write a method call. The simpler and more common way is to use the arrow notation:
my $fred = Critter->find("Fred"); $fred->display("Height", "Weight");You should already be familiar with the use of the
->operator with references. In fact, since$fredabove is a reference to an object, you could think of the method call as just another form of dereferencing.Whatever is on the left side of the arrow, whether a reference or a class name, is passed to the method subroutine as its first argument. So the above code is mostly equivalent to:
my $fred = Critter::find("Critter", "Fred"); Critter::display($fred, "Height", "Weight");How does Perl know which package the subroutine is in? By looking at the left side of the arrow, which must be either a package name or a reference to an object, i.e., something that has been blessed to a package. Either way, that’s the package where Perl starts looking. If that package has no subroutine with that name, Perl starts looking for it in any base classes of that package, and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With