in reply to Re: initialize all values in a hash
in thread initialize all values in a hash

"You could do it with a tied hash, but I can't find a module that does this on CPAN, so you'd need to do it yourself."

OK, I've just gone and uploaded Hash::DefaultValue to CPAN. Usage:

tie my %hash, 'Hash::DefaultValue', 60; $hash{foo} = 8; say $hash{foo}; # says 8 say $hash{bar}; # says 60
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re^3: initialize all values in a hash
by DrHyde (Prior) on May 18, 2012 at 14:03 UTC

      Oh, that's annoying. In fairness, a documented feature of mine is that it explicitly avoids autovivifying keys. So with Tie::Hash::Vivify, this is true:

      tie my %hash, 'Tie::Hash::Vivify', sub { 10 }; say $hash{foo}; # says 10 my $is_this_true = exists $hash{foo};

      Whereas this is false:

      tie my %hash, 'Hash::DefaultValue', sub { 10 }; say $hash{foo}; my $is_this_true = exists $hash{foo};

      Another feature of Hash::DefaultValue is that the coderef gets passed a copy of the key, so can use that information when generating the default value.

      tie my %hash, 'Hash::DefaultValue', sub { uc }; say $hash{foo}; # says "FOO"
      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
        I mostly use Tie::Hash::Vivify to prevent autovivification thus:
        my $hashref = Tie::Hash::Vivify->new( sub { confess("No auto-vivifying!\n".Dumper(\@_)) } )
        to avoid those annoyingly hard-to-track-down bugs where you've typoed a hash key.