The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


Tie::Hash::Vivify - Create hashes that autovivify in interesting ways.


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.


    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
    # ...


You can also create your magic hash in an objecty way:


    my $hashref = Tie::Hash::Vivify->new(sub { "my default" });


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.


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.


Luke Palmer, lrpalmer gmail com (original author)

David Cantrell <> (current maintainer)


Copyright (C) 2005 by Luke Palmer

Some parts Copyright 2010 David Cantrell <>.

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.