2

I'm new to OOPerl, and wanted to know how I can reference an instance of a class within that class (i.e. $this in PHP) so that I'm able to call its "private" methods

To make it more clear:

in PHP for instance:

class Foo {
    public function __construct(){

    }

    public function doThis(){
         $that = $this->doThat(); //How to reference a "private" function in perl that is defined in the same class as the calling function?
         return $that;
    }

    private function doThat(){
         return "Hi";
    }
}
a7omiton
  • 1,597
  • 4
  • 34
  • 61
  • 2
    http://stackoverflow.com/questions/451521/how-do-i-make-private-functions-in-a-perl-module – Ashalynd Aug 02 '14 at 23:23
  • Your question is unclear. Is it that you simply need to understand that you must do `my $self = shift(@_)` at the top of the method? – tchrist Aug 03 '14 at 00:18
  • @a7omiton: If you mean *"how can I access the object on which a method has been called"* then see my answer below. Otherwise please clarify your question. I am puzzled that Ashalynd's reference has helped you as it doesn't seem to relate to your question. – Borodin Aug 03 '14 at 00:30

1 Answers1

2

Perl methods are ordinary subroutines that expect the first element of their parameter array @_ to be the object on which the method is called.

An object defined as

my $object = Class->new

can then be used to call a method, like this

$object->method('p1', 'p2')

The customary name is $self, and within the method you assign it as an ordinary variable, like this

sub method {
  my $self = shift;
  my ($p1, $p2) = @_;

  # Do stuff with $self according to $p1 and $p2

}

Because the shift removes the object from @_, all that is left are the explicit parameters to the method call, which are copied to the local parameter variables.

There are ways to make inaccessible private methods in Perl, but the vast majority of code simply trusts the calling code to do the right thing.

Borodin
  • 126,100
  • 9
  • 70
  • 144
  • I wasn't fully aware of having to declare $self in each method, that was pretty helpful from this post as well as the referenced link in comments :) – a7omiton Aug 03 '14 at 00:36
  • I understand the way to do it now; declare $self and then call the method i.e. $self->method within the function that wants to use the other function – a7omiton Aug 03 '14 at 00:38
  • 1
    Ah I see. You want to call one method from within another. Yes, just take `$self` from `@_` as I described and then you can call `$self->other_method` just as the calling code would. Perl does very "hands on" object oriented code, but because of that it taught me more than any other language ever has – Borodin Aug 03 '14 at 02:42