Tying Arrays
A class implementing a tied array must define at least the methods TIEARRAY, FETCH, and STORE. There are many optional methods: the ubiquitous UNTIE and DESTROY methods, of course, but also
the STORESIZE and
FETCHSIZE methods used to provide
$#array and scalar(@array) access. In addition, CLEAR is triggered when Perl needs to empty
the array, and EXTEND when Perl
would have preextended allocation in a real array.
You may also define the POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS methods if you want the corresponding Perl functions to work on
the tied array. The Tie::Array class can serve as a base class to implement the first
five of those functions in terms of FETCH and STORE. (Tie::Array’s default implementation of
DELETE and EXISTS simply calls croak.) As long as you define FETCH and STORE, it doesn’t matter what kind of data
structure your object contains.
On the other hand, the Tie::StdArray class (defined in the standard Tie::Array module) provides a base class
with default methods that assume the object contains a regular array.
Here’s a simple array-tying class that makes use of this. Because it
uses Tie::StdArray as its base
class, it only needs to define the methods that should be treated in a
nonstandard way:
#!/usr/bin/perl package ClockArray; use Tie::Array; our @ISA = "Tie::StdArray"; sub FETCH { my($self,$place) = @_; $self–>[ $place % 12 ]; } sub STORE { my($self,$place,$value) = @_; $self–>[ $place % 12 ] = $value; } package main; tie my @array, ...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