NAME
Tie::Hash::Vivify - Create hashes that autovivify in interesting ways.
DESCRIPTION
This module implements a hash where if you read a key that doesn't exist, it will call a code reference to fill that slot with a value.
SYNOPSIS
use Tie::Hash::Vivify;
my $default = 0;
tie my %hash => 'Tie::Hash::Vivify', sub { "default" . $default++ };
print $hash{foo}; # default0
print $hash{bar}; # default1
print $hash{foo}; # default0
$hash{baz} = "hello";
print $hash{baz}; # hello
my $hashref = Tie::Hash::Vivify->new(sub { "default" });
$hashref->{foo}; # default
# ...
OBJECT-ORIENTED INTERFACE
You can also create your magic hash in an objecty way:
new
my $hashref = Tie::Hash::Vivify->new(sub { "my default" });
"INFECTING" CHILD HASHES
By default, hashes contained within your hash do *not* inherit magical vivification behaviour. If you want them to, then pass some extra params thus:
tie my %hash => 'Tie::Hash::Vivify', sub { "default" . $default++ }, infect_children => 1;
my $hashref = Tie::Hash::Vivify->new(sub { "my default" }, infect_children => 1);
This will not, however, work if the child you insert is already tied - that would require re-tieing it, which would lose whatever magic behaviour the original had.
BUGS
scalar(%tied_hash)
appears to not work properly on perl 5.8.2 and earlier. I don't really care, and frankly nor should you. In the unlikely event that you do care, please submit a patch.
AUTHORS
Luke Palmer, lrpalmer gmail com (original author)
David Cantrell <david@cantrell.org.uk> (current maintainer)
COPYRIGHT AND LICENSE
Copyright (C) 2005 by Luke Palmer
Some parts Copyright 2010 David Cantrell <david@cantrell.org.uk>.
This software is free-as-in-speech software, and may be used, distributed, and modified under the terms of either the GNU General Public Licence version 2 or the Artistic Licence. It's up to you which one you use. The full text of the licences can be found in the files GPL2.txt and ARTISTIC.txt, respectively.