" versus passing a class / object as the first parameter? From perldoc perlobj (cited in t...">

What is the difference between calling a method using "->" versus passing a class / object as the first parameter?

From perldoc perlobj (cited in this excellent answer):

 my $fred = Critter->find("Fred"); $fred->display("Height", "Weight"); 

... the code above is basically equivalent:

 my $fred = Critter::find("Critter", "Fred"); Critter::display($fred, "Height", "Weight"); 

What exactly is the difference, leaving aside error checking to make sure that the first parameter is a blessed object or a valid class name? For example. why is it mostly , but not quite the same?

+7
source share
1 answer

Say Critter is a subclass that does not define find or display or both! Matching is not straightforward because the hardware subheadings do not search for the method, as perlobj's documentation explains.

How does Perl know which package the routine is in? Look at the left side of the arrow, which should be either the name of the package or a reference to the object, that is, what was blessed by the package. In any case, this is the package in which Perl begins to search. If this package does not have a routine with this name, Perl starts looking for it in any base classes of this package, etc.

With sub, you need to know exactly where it is statically, or your program will die . To call a method, you only need to specify where to look for it.

For example:

 #! /usr/bin/env perl package Critter; sub new { bless {}, shift } sub display { ref($_[0]) . " display" } package SuperCritter; @SuperCritter::ISA = qw/ Critter /; package main; my $super = SuperCritter->new; # one of these things is not like the other warn $super->display; warn Critter::display($super); warn SuperCritter::display($super); 

Output:

  SuperCritter display at ./call-demo line 14.
 SuperCritter display at ./call-demo line 15.
 Undefined subroutine & SuperCritter :: display called at ./call-demo line 16. 
+15
source

All Articles