It can also be done using a tied hash (with a speed penalty). I don't see an existing module on CPAN after a quick look, but it's it's easy to write your own.
{
package Hash::WithDefault;
use Tie::Hash qw( );
BEGIN { our @ISA = 'Tie::ExtraHash'; }
use constant IDX_HASH => 0;
use constant IDX_DEFAULT => 1;
use constant NEXT_IDX => 2;
sub FETCH {
my ($self, $key) = @_;
return ( exists( $self->[IDX_HASH]{$key} )
? $self->[IDX_HASH]{$key}
: $self->[IDX_DEFAULT]
);
}
}
{
tie my %hash, 'Hash::WithDefault', 'not in the alphabet';
%hash = (
a => 'a vowel',
b => 'a consonant',
);
print("$_: $hash{$_}\n") for qw( a b ~ );
}
Output:
a: a vowel
b: a consonant
~: not in the alphabet