Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is the difference between calling a method via "->" vs passing class/object as first parameter?

Tags:

object

oop

perl

From perldoc perlobj (quoted in this excellent answer):

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

... the above code is mostly equivalent to:

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

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

like image 769
DVK Avatar asked May 28 '12 12:05

DVK


1 Answers

Say Critter is a subclass that doesn’t define find or display—or both! The correspondence isn’t one-for-one because hardwired sub calls don’t perform method lookup, as the perlobj documentation explains.

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.

With a sub, you have to know exactly where it is statically, or your program will die. To call a method, you need only specify where to begin searching 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.
like image 126
Greg Bacon Avatar answered Oct 19 '22 02:10

Greg Bacon