Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- sub my_private_function {
- ...
- };
- package TestPrivate;
- require 5.004;
- use strict;
- use warnings;
- use Carp;
- use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
- require Exporter;
- @ISA = qw(Exporter AutoLoader);
- our @EXPORT_OK = qw( public_function );
- our @EXPORT = qw( );
- $VERSION = '0.01';
- sub new {
- my ( $class, %args ) = @_;
- my $self = {};
- bless( $self, $class );
- $self->private_function("THIS SHOULD BE PRIVATE");
- $self->{public_variable} = "This is public";
- return $self;
- }
- sub public_function {
- my $self = shift;
- my $new_text = shift;
- $self->{public_variable} = $new_text;
- print "Public Variable: $self->{public_variable}n";
- print "Internal Variable: $self->{internal_variable}n";
- }
- sub private_function {
- my $self = shift;
- my $new_text = shift;
- $self->{internal_variable} = $new_text;
- }
- #!/usr/bin/perl
- use strict;
- use TestPrivate 'public_function';
- my $foo = new TestPrivate();
- $foo->public_function("Changed public variable");
- $foo->private_function("I changed your private variable");
- $foo->public_function("Changed public variable again");
- $foo->{internal_variable} = "Yep, I changed your private variable again!";
- $foo->public_function("Changed public variable the last time");
- Public Variable: Changed public variable
- Internal Variable: THIS SHOULD BE PRIVATE
- Public Variable: Changed public variable again
- Internal Variable: I changed your private variable
- Public Variable: Changed public variable the last time
- Internal Variable: Yep, I changed your private variable again!
- caller eq __PACKAGE__ or die;
- my $priv_func1 = sub { my $self = shift; say 'func1'; };
- sub public_sub {
- my $self = shift;
- $priv_func1->( $self );
- }
- my $priv_func1 = sub {
- my $self = shift; say 'func1';
- };
- sub public_sub {
- my $self = shift;
- $self->$priv_func1(@_);
- }
- 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( );
Add Comment
Please, Sign In to add comment