Приглашаем посетить
Паустовский (paustovskiy-lit.ru)

Tie::Array::Bounded

Previous Table of Contents Next

Tie::Array::Bounded


package Tie::Array::Bounded;

use strict;

use warnings;

use Carp;



use base qw(Tie::Array);



our $VERSION = '0.01';



sub TIEARRAY

{

  my ($class, %arg) = @_;

  my ($upper, $lower) = delete @arg{qw(upper lower)};

  croak "Illegal arguments in tie" if %arg;

  $lower ||= 0;

  croak "No upper bound for array" unless $upper;

  /\D/ and croak "Array bound must be integer"

    for ($upper, $lower);

  croak "Upper bound < lower bound" if $upper < $lower;

  return bless { upper => $upper,

                 lower => $lower,

                 array => []

               }, $class;

}



sub _bound_check

{

  my ($self, $index) = @_;

  my ($upper, $lower) = @{$self}{qw(upper lower)};

  croak "Index $index out of range [$lower, $upper]"

    if $index < $lower || $index > $upper;

}



sub STORE

{

  my ($self, $index, $value) = @_;

  $self->_bound_check($index);

  $self->{array}[$index] = $value;

}



sub FETCH

{

  my ($self, $index) = @_;

  $self->_bound_check($index);

  $self->{array}[$index];

}



sub FETCHSIZE

{

  my $self = shift;

  scalar @{$self->{array}};

}



sub STORESIZE

{

  my ($self, $size) = @_;

  $self->_bound_check($size-1);

  $#{$self->{array}} = $size - 1;

}



1;



__END__



=head1 NAME



Tie::Array::Bounded - Bounded arrays



=head1 SYNOPSIS



  use Tie::Array::Bounded;

  tie @array, "Tie::Array::Bounded", upper => 100;



=head1 DESCRIPTION



C<Tie::Array::Bounded> is a subclass of L<Tie::Array> that

allows you to create arrays which perform bounds checking

upon their indices. A fatal exception will be thrown upon

an attempt to go outside specified bounds.



Usage:



  tie @array, "Tie::Array::Bounded",

              upper => $upper_limit [, lower => $lower_limit]



A mandatory upper limit is specified with the C<upper> keyword.

An optional lower limit is specified with the C<lower> keyword;

the default is 0.  Each specifies the limit of array indices

that may be used.  Any attempt to exceed them results in the

fatal exception "index <index> out of range [<lower>, <upper>]".



=head1 AUTHOR



Peter Scott, C<Peter@PSDT.com>



=head1 SEE ALSO



L<perltie>, L<Tie::Array>.



=cut

    Previous Table of Contents Next