in reply to Fixed Array size
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 | |
by jryan (Vicar) on Sep 12, 2002 at 22:10 UTC |