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

Hi everyone, I am writing a module which contains some functions that aren't needed to be accessed externally, they don't need to be exported by default. They only perform tasks relevant to the internal workings of the module. Is there a way to provide private access to these functions for this module only and prevent any calls from external scripts?
  • Comment on Visibility of Subroutines within modules,

Replies are listed 'Best First'.
Re: Visibility of Subroutines within modules,
by Fletch (Bishop) on Mar 25, 2002 at 02:18 UTC

    You can rely on convention, and simply name things with an underscore as the first character of the sub's name (and put in a note to the fact). If anyone gets burned by using the private interface, it's their own fault.

    A truly private option would be to stash coderefs in a lexically declared hash.

    package Foo; my %hidden = ( bar => sub { print "Bar\n"; }, ... ); sub something_public { my( $baz, $quux ) = @_; return $hidden{bar}->( $baz + 5, reverse $quux ); }
      (disregard the mispost above) In reference to the hash declaration am I able to declare variables contained within the hash like my %hidden = ( bar=>sub { my $foo = shift; print $foo; } ); Instead of using one line of code per entry?
Re: Visibility of Subroutines within modules,
by broquaint (Abbot) on Mar 25, 2002 at 17:19 UTC
    You could use miyagawa's Attribute::Protected module which let's you implement C++/Java style encapsulation on your methods.
    package SomeClass; use Attribute::Protected; sub new { return bless {}, shift } sub foo : Public { print "am in public foo()\n"; } sub bar : Private { print "am in private bar()\n"; } qq[end of package]; package main; $x = SomeClass->new(); $x->foo(); # fine - foo is public $x->bar(); # dies - bar is private

    HTH

    broquaint

      Thanks to all the replies, I'll have a look at both techniques mentioned. ceedee