in reply to Fixed Array size

Sure, easy; like the man said, just use tie:
package Tie::FixedArray; use Carp; sub TIEARRAY { my @new = (undef) x $_[1]; bless \@new, $_[0] } sub FETCHSIZE { scalar @{$_[0]} } sub STORE { croak "Element out of bounds$!" if (abs($_[1]) > @{$_[0]}); $_[0]->[$_[1]] = $_[2] } sub FETCH { croak "Element out of bounds$!" if (abs($_[1]) > @{$_[0]}); $_[0]->[$_[1]] } sub EXISTS { exists $_[0]->[$_[1]] } sub CLEAR { @{$_[0]} = (undef) x @{$_[0]} } sub DELETE { delete $_[0]->[$_[1]] } sub SPLICE { my $self = shift; croak "Elements can't be removed from fixed length + arrays$!" if (@_ < 2); if (@_ > 2) { my ($off,$len) = (shift,shift); croak "Element out of bounds$!" if ( (abs($off)+$len) > @{$self}); croak "Elements can't be removed from fixed le +ngth arrays$!" if ($len > @_); croak "Elements can't be removed from fixed le +ngth arrays$!" if ($len < @_); return splice (@{$self},$off,$len,@_); } elsif (($_[0] == 0) && ($_[1] == 0)) {} else { croak "Elements can't be removed from fixed le +ngth arrays$!" } } sub STORESIZE { croak "Elements can't be added/removed to fixed le +ngth arrays$!" } sub PUSH { croak "Elements can't be added to fixed length arr +ays$!" } sub POP { croak "Elements can't be removed from fixed length + arrays$!" } sub SHIFT { croak "Elements can't be removed from fixed length + arrays$!" } sub UNSHIFT { croak "Elements can't be added to fixed length arr +ays$!" } sub EXTEND { croak "Fixed length arrays can't be extended$!" } package main; use strict; use warnings 'all'; # 4 element fixed array my $object = tie my @somearray,'Tie::FixedArray', 4; $somearray[3] = 'hi'; print $somearray[3]; $somearray[5] = 'hello!' # watch it crash and burn!

Update: Accidentally mixed up carp and croak. Fixed.
Update: Fixed splice mistake mentioned by theorbtwo.

Replies are listed 'Best First'.
Re: Re: Fixed Array size
by theorbtwo (Prior) on Sep 12, 2002 at 21:49 UTC

    Careful, jryan, there are uses of SPLICE that are valid for fixed-length arrays, to whit, where scalar(@list)==$length. Also, BTW, for a very different implementation of this same idea, read perltie; the example for arrays is none other then a length-limited array. (Not quite the same thing -- this requires there always be exactly N elements; the class in perltie requires there be at most N elements. The difference is rather pendatic.)


    Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by responing to this node).

      You are very correct. Fixed.