Array-Tying Methods
That’s the simple way. Now for some nitty-gritty details. To demonstrate, we’ll implement an array whose bounds are fixed at its creation. If you try to access anything beyond those bounds, an exception is raised. For example:
use BoundedArray; tie @array, "BoundedArray", 2; $array[0] = "fine"; $array[1] = "good"; $array[2] = "great"; $array[3] = "whoa"; # Prohibited; displays an error message.
The preamble code for the class is as follows:
package BoundedArray; use Carp; use strict;
To avoid having to define SPLICE later, we’ll inherit from the
Tie::Array class:
use Tie::Array;
our @ISA = ("Tie::Array");-
CLASSNAME–>TIEARRAY(LIST) As the constructor for the class,
TIEARRAYshould return a blessed reference through which the tied array will be emulated.In this next example, just to show you that you don’t really have to return an array reference, we’ll choose a hash reference to represent our object. A hash works out well as a generic record type: the value in the hash’s “
BOUND” key will store the maximum bound allowed, and its “DATA” value will hold the actual data. If someone outside the class tries to dereference the object returned (doubtless thinking it an array reference), an exception is raised.sub TIEARRAY { my $class = shift; my $bound = shift; confess "usage: tie(\@ary, 'BoundedArray', max_subscript)" if @_ || $bound =~ /\D/; return bless { BOUND => $bound, DATA => [] }, $class; }We can now say:
tie(@array, "BoundedArray", 3); # maximum allowable index is ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access