in reply to Having a "default" hash value!

You're right.. the best way to do this is to just check for the key's existence in the hash (perhaps factored into some function). But since you asked for a snazzy Perlish way, you could tie the hash to return a specific value when the key doesn't exist.

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:

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]; }
The to use it...
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