1Tie::Memoize(3pm) Perl Programmers Reference Guide Tie::Memoize(3pm)
2
3
4
6 Tie::Memoize - add data to hash when needed
7
9 require Tie::Memoize;
10 tie %hash, 'Tie::Memoize',
11 \&fetch, # The rest is optional
12 $DATA, \&exists,
13 {%ini_value}, {%ini_existence};
14
16 This package allows a tied hash to autoload its values on the first
17 access, and to use the cached value on the following accesses.
18
19 Only read-accesses (via fetching the value or "exists") result in calls
20 to the functions; the modify-accesses are performed as on a normal
21 hash.
22
23 The required arguments during "tie" are the hash, the package, and the
24 reference to the "FETCH"ing function. The optional arguments are an
25 arbitrary scalar $data, the reference to the "EXISTS" function, and
26 initial values of the hash and of the existence cache.
27
28 Both the "FETCH"ing function and the "EXISTS" functions have the same
29 signature: the arguments are "$key, $data"; $data is the same value as
30 given as argument during tie()ing. Both functions should return an
31 empty list if the value does not exist. If "EXISTS" function is
32 different from the "FETCH"ing function, it should return a TRUE value
33 on success. The "FETCH"ing function should return the intended value
34 if the key is valid.
35
37 The structure of the tied() data is an array reference with elements
38
39 0: cache of known values
40 1: cache of known existence of keys
41 2: FETCH function
42 3: EXISTS function
43 4: $data
44
45 The rest is for internal usage of this package. In particular, if
46 TIEHASH is overwritten, it should call SUPER::TIEHASH.
47
49 sub slurp {
50 my ($key, $dir) = shift;
51 open my $h, '<', "$dir/$key" or return;
52 local $/; <$h> # slurp it all
53 }
54 sub exists { my ($key, $dir) = shift; return -f "$dir/$key" }
55
56 tie %hash, 'Tie::Memoize', \&slurp, $directory, \&exists,
57 { fake_file1 => $content1, fake_file2 => $content2 },
58 { pretend_does_not_exists => 0, known_to_exist => 1 };
59
60 This example treats the slightly modified contents of $directory as a
61 hash. The modifications are that the keys fake_file1 and fake_file2
62 fetch values $content1 and $content2, and pretend_does_not_exists will
63 never be accessed. Additionally, the existence of known_to_exist is
64 never checked (so if it does not exists when its content is needed, the
65 user of %hash may be confused).
66
68 FIRSTKEY and NEXTKEY methods go through the keys which were already
69 read, not all the possible keys of the hash.
70
72 Ilya Zakharevich <mailto:perl-module-hash-memoize@ilyaz.org>.
73
74
75
76perl v5.28.2 2018-03-01 Tie::Memoize(3pm)