in reply to Default Hash Key

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 ~ ); }


a: a vowel b: a consonant ~: not in the alphabet

Replies are listed 'Best First'.
Re^2: Default Hash Key
by alexm (Chaplain) on May 02, 2008 at 10:21 UTC
      Thanks for looking, but that module doesn't do what the OP wants as far as I can tell.

        That's true... I assumed it did from the NAME section description :-(

        I guess that Hash::WithAlternatives should've been a more appropiate name for that module.

Re^2: Default Hash Key
by jethro (Monsignor) on May 02, 2008 at 14:04 UTC
    If I read the doc of Tie::Hash correctly, you should have used
    use Tie::StdHash qw( );
    Tie::Hash only provides a subset of the necessary hash methods

      Tie::Hash, Tie::StdHash and Tie::ExtraHash are in Tie/, thus use Tie::Hash; is needed even if you want to use the Tie::StdHash class.

      >perl -e"use Tie::StdHash qw( );" Can't locate Tie/ in @INC (@INC contains: c:/Progs/perl588/l +ib c:/Progs/perl588/site/lib .) at -e line 1. BEGIN failed--compilation aborted at -e line 1.

      Notice that I didn't actually inherit from Tie::Hash. I didn't inherit from Tie::StdHash either because it doesn't provide any means to store object attributes such as the default value. Tie::ExtraHash does.