How do I make private functions in a Perl module?

前端 未结 9 941
后悔当初
后悔当初 2020-12-23 20:43

I am working on a little Perl module and for some reason I had the test driver script that was using my new module call one of the functions that I thought would be private,

9条回答
  •  天涯浪人
    2020-12-23 20:54

    Just check caller:

    package My;
    
    sub new {
      return bless { }, shift;
    }
    
    sub private_func {
      my ($s, %args) = @_;
      die "Error: Private method called"
        unless (caller)[0]->isa( ref($s) );
    
      warn "OK: Private method called by " . (caller)[0];
    }
    
    sub public_func {
      my ($s, %args) = @_;
    
      $s->private_func();
    }
    
    package main;
    
    my $obj = My->new();
    
    # This will succeed:
    $obj->public_func( );
    
    # This will fail:
    $obj->private_func( );
    

提交回复
热议问题