Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Re^3: initialize all values in a hash

by DrHyde (Prior)
on May 18, 2012 at 14:03 UTC ( #971310=note: print w/ replies, xml ) Need Help??

Comment on Re^3: initialize all values in a hash
Re^4: initialize all values in a hash
by tobyink (Abbot) on May 18, 2012 at 14:27 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.

        The autovivification module is pretty good for this kind of thing. Offers you the ability to simply switch off autovivification, warn about it, or croak. Rather than being tied to a particular hash, it's lexically scoped. And it's context-sensitive, so you could decide that 'store' operations are allowed to autovivify, like:

        { no autovivification qw(strict); use autovivification qw(store); my %hash; $hash{foo}{bar}{baz} = 1; # autovivifies OK delete $hash{fool}{bar}{baz}; # dies }

        If only autovivification weren't so tricky to type.

        perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://971310]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (14)
As of 2014-07-31 19:15 GMT
Find Nodes?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:

    Results (251 votes), past polls