Tying Hashes

Accesses to tied hash tables are fully supported, unlike arrays. The tie-hash facility allows you to trap operations on the entire hash table (%h = ()), accesses to individual elements, and queries (exists, defined, each, keys, and values). Table 9.3 shows how these actions are mapped to method invocations on the tied object.

Table 9-3. tie and Hash Access

When you say:

Perl translates it to:

tie %h, 'Foo', 'a' => 1
$obj = Foo-->TIEHASH('a',1);
$h{a}
$obj-->FETCH ('a')
$h{a} = 1
$obj-->STORE ('a', 1)
delete $h{a}
$obj-->DELETE('a')
exists $h{a}
$obj-->EXISTS('a')
keys (%h),values(%h)
each (%h)
$lk = $obj-->FIRSTKEY ();
do {
   $val = $obj-->FETCH{$lk};
} while ($lk = $obj-->NEXTKEY($lk));
%h = ()
$obj-->CLEAR()
%h = (a=> 1)
$obj-->CLEAR()
$obj-->STORE('a',1)
untie %h
$obj-->DESTROY()

FIRSTKEY and NEXTKEY are expected to return the next key in the sequence. This suffices if keys is invoked by the calling code; but if values or each is called, it calls FETCH for each key.

The most common (and natural-looking) use of tie is as a frontend for DBM files, which, as we mentioned earlier, are disk-based hash tables. Perl comes enabled with various flavors of DBM support. The following example uses the SDBM module, which comes with the standard Perl distribution:

use Fcntl; use SDBM_File; tie (%h, 'SDBM_File', 'foo.dbm', O_RDWR|O_CREAT, 0640) || die $!; # Open dbm file $h{a} = 10; # Write to file transparently while (($k, $v) = each %h) { # Iterate over ...

Get Advanced Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.