smackdab has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I am creating a smallish hash like this:
{part1}{part2} = value

I want to have "default" values for part1 or part2 if they are not defined...
$hash{part1}{""} = 100; $hash{part1}{part2} = 200;
So GetHash($part1, $part2) would try and return:
$hash{part1}{part2} || $hash{part1}{""};
I think this will work, but could use your advice frist ;-)

thanks

Replies are listed 'Best First'.
Re: "" in hash as a default?
by tadman (Prior) on Mar 23, 2002 at 00:26 UTC
    This is perfectly valid. You can even do some tricks with it, like:
    my %way_of = ( the_sword => sub{do('sword',@_)}, the_gun => sub{do('gun',@_)}, "" => sub{do('default',@_)}, ); my $what = $something; my $stuff = $something_else; &{$way_of{$what} || $way_of{""}}($stuff);
    Great for building switch-type handlers with a default case.

    In fact, Benchmark seems to indicate that this type of handler is faster than a series of equivalent if statements, such as:
    if ($what eq 'the_sword') { do('sword', $stuff); } elsif ($what eq 'the_gun') { do('gun', $stuff); } else { do('default', $stuff); }
    A hash lookup is very fast compared to evaluating a long if structure, especially as the number of elements increases.

    However, note that this speed improvement is only possible if you only declare your hash table once. If it is declared inside a subroutine, it will be re-created every time that routine is call, slowing down processing substantially.