Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Default Hash Key

by ikegami (Patriarch)
on May 02, 2008 at 01:05 UTC ( [id://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

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/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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://684069]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (2)
As of 2025-06-21 17:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.