Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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

Output:

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


Comment on Re: Default Hash Key
Select or Download Code
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/Hash.pm, 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/StdHash.pm 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2015-07-05 09:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (61 votes), past polls