Tie::Memoize - add data to hash when needed
require Tie::Memoize;tie %hash, 'Tie::Memoize', \&fetch,# The rest is optional $DATA, \&exists, {%ini_value}, {%ini_existence};
This package allows a tied hash to autoload its values on the first access, and to use the cached value on the following accesses.
Only read-accesses (via fetching the value orexists
) result in calls to the functions; the modify-accesses are performed as on a normal hash.
The required arguments duringtie
are the hash, the package, and the reference to theFETCH
ing function. The optional arguments are an arbitrary scalar $data, the reference to theEXISTS
function, and initial values of the hash and of the existence cache.
Both theFETCH
ing function and theEXISTS
functions have the same signature: the arguments are$key, $data
; $data is the same value as given as argument during tie()ing. Both functions should return an empty list if the value does not exist. IfEXISTS
function is different from theFETCH
ing function, it should return a TRUE value on success. TheFETCH
ing function should return the intended value if the key is valid.
The structure of the tied() data is an array reference with elements
0: cache of known values1: cache of known existence of keys2: FETCH function3: EXISTS function4: $data
The rest is for internal usage of this package. In particular, if TIEHASH is overwritten, it should call SUPER::TIEHASH.
sub slurp { my ($key, $dir) = shift; open my $h, '<', "$dir/$key" or return; local $/; <$h># slurp it all}sub exists { my ($key, $dir) = shift; return -f "$dir/$key" }tie %hash, 'Tie::Memoize', \&slurp, $directory, \&exists, { fake_file1 => $content1, fake_file2 => $content2 }, { pretend_does_not_exists => 0, known_to_exist => 1 };
This example treats the slightly modified contents of $directory as a hash. The modifications are that the keysfake_file1 andfake_file2 fetch values $content1 and $content2, andpretend_does_not_exists will never be accessed. Additionally, the existence ofknown_to_exist is never checked (so if it does not exists when its content is needed, the user of %hash may be confused).
FIRSTKEY and NEXTKEY methods go through the keys which were already read, not all the possible keys of the hash.
Ilya Zakharevichmailto:perl-module-hash-memoize@ilyaz.org.
Perldoc Browser is maintained by Dan Book (DBOOK). Please contact him via theGitHub issue tracker oremail regarding any issues with the site itself, search, or rendering of documentation.
The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via thePerl issue tracker, themailing list, orIRC to report any issues with the contents or format of the documentation.