Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: Default Hash Key

by ikegami (Pope)
on May 02, 2008 at 01:05 UTC ( #684069=note: print w/ replies, xml ) Need Help??

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

Comment on Re: Default Hash Key
Select or Download Code
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.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2015-11-26 03:44 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (696 votes), past polls