Reputation: 28437
For me, Perl references are a hard thing to grasp. When reading to some OO-like scripts that use object methods, I never saw the object used as a reference. Even for big objects, that would benefit from being used as a reference instead of being copied to a subroutine (method).
PerlMaven says that:
$p->a_method($value);
Behind the scenes, perl will run
a_method($p, $value);
But if $p
is huge object, wouldn't you want to pass it as a reference?
a_method(\$p, $value)
I have always understood that passing by reference can lead to a significant speed increase if the object is large. In OO, it is quite likely that you are working with large objects (e.g. a huge XML::Twig
). So how would you call a method on such an object, when actually passing it as a reference to the subroutine?
Upvotes: 0
Views: 395
Reputation: 241858
$p
already contains a reference to the object. Method calls require a reference to the object, and it's this reference that's passed to the sub. So, $self is always a reference. See perlobj and bless.
#! /usr/bin/perl
use strict;
use warnings;
use feature 'say';
{ package Class;
sub new { bless {}, __PACKAGE__ }
sub inf { ref shift }
}
my $o = 'Class'->new;
say $o->inf ? 'reference' : 'not a reference';
Output:
reference
Upvotes: 9