sudeeps has asked for the wisdom of the Perl Monks concerning the following question:

Hi Perl monks, How can I create a subroutine in an object oriented perl module so that it can be used internally within the module and also externally? I was not able to find any pages mentioning about it. Thank you for your help in advance.

Replies are listed 'Best First'.
Re: perl module subroutine
by Corion (Patriarch) on Aug 26, 2010 at 08:11 UTC

    Every subroutine can be used from the object and externally. There are no private methods/subroutines in Perl.

    There is one thing to remember - you cannot (or rather, should not try to) make a subroutine that can act as both, a method and a plain subroutine. No good comes of that.

    package My::Class; sub my_method { my ($self,@args) = @_; print "@args\n"; }; sub other_method { my ($self,@args) = @_; $self->my_method('hello'); }; package main; My::Class->my_method('world');
      > There are no private methods/subroutines in Perl.

      Just for completeness, one can easily achieve the effect of "private subs" by using lexical coderefs.

      { package MyClass; my $private= sub { ... }; $private->(); # call as private function }

      Sorry for nitpicking :)

      UPDATE:

      and of course

      $self->$private(); # call as private method

      to pass thru $self as first argument.

      Cheers Rolf

      Thank you Corion, that helped me a lot