package Example::Module; use strict; { # this variable is not accessible outside of the block # that it's in. thus, any access to it must go through # the subroutines defined in this block. my $variable; sub accumulate { $variable += $_ for @_ } sub printvalue { print $variable, $/ } } 1; #### use Example::Module; Example::Module::accumulate(5,6,7); Example::Module::printvalue; #### package Example::Module; use strict; { my $value; # this lexical variable stores a subroutine that is only # accessible from within this block. my $add = sub { $value += $_[0] }; sub accumulate { $add->($_) for @_ } sub printvalue { print $value, $/ } } 1; #### package Example::Module; use strict; # note, we don't actually have to use the reference that we # bless. we just need it for its unique reference id. sub new { bless {}, shift } { my %value; my %counter; sub accumulate { my $self = shift; for (@_) { $value{ $self } += $_; $counter{ $self }++; } } sub printvalue { my $self = shift; printf "%s has value %2d from %2d iterations.\n", $self, $value{$self}, $counter{$self}; } # prevent memory leaks. DESTROY { my $self = shift; delete $value{$self}; delete $counter{$self}; } } 1;