in reply to Having a "default" hash value!
I was surprised not to see something that does this on CPAN. Perhaps I didn't search for the right thing. Either way, it's a pretty simple tie interface:
The to use it...package Tie::Hash::DefaultVal; require Tie::Hash; @ISA = qw[Tie::ExtraHash]; sub TIEHASH { my ($pkg, $default) = @_; bless [ {}, $default ], $pkg; } sub FETCH { my ($self, $key) = @_; exists $self->[0]{$key} ? $self->[0]{$key} : $self->[1]; }
tie my %h, Tie::Hash::DefaultVal => "default-val"; %h = ( foo => "foo-val", bar => "bar-val" ); print "\$h{$_} = $h{$_}\n" for qw[ foo bar nonexistant ]; __OUTPUT__ $h{foo} = foo-val $h{bar} = bar-val $h{nonexistant} = default-val
blokhead
|
|---|