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

trying out the code btrott suggested in storing data via 2 sibling keys I found (using Data::Dumper) that the subroutines for the tied has only accept the first key, defeating the original purpose of the code. Am I missing something or do i need to look at a full fledged OO solution rather than just using Ties?
  • Comment on Tied Hash to emulate double-key hash only accepts one key

Replies are listed 'Best First'.
Re: Tied Hash to emulate double-key hash only accepts one key
by bikeNomad (Priest) on Jun 21, 2001 at 21:27 UTC
    If you use the pseudo-two-dimensional index (using a comma):
    $hash{'a', 'b'}
    you only get a single key, that is, "a\034b" (unless you change $; ). This is like AWK's simulation of multi-dimensional arrays/hashes, right down to the use of SUBSEP ("\034") as a delimiter. Look at the following with Data::Dumper (I changed $; so you could see it):
    use strict; use Tie::Hash; package Tie::HashNKeys; use base 'Tie::StdHash'; sub TIEHASH { my $class = shift; bless {}, $class; } sub STORE { $_[0]->{ join $;, sort split /$;/, $_[1] } = $_[2]; } sub FETCH { $_[0]->{ join $;, sort split /$;/, $_[1] }; } package main; use Data::Dumper; $; = '~'; # so it can be seen tie my %hash, 'Tie::HashNKeys'; $hash{'csUsers','csGroups'} = 'foo'; print $hash{'csGroups','csUsers'}; ## prints 'foo' print Dumper(\%hash);

      Update from the front lines: well, it seems to be working part of the time. Revelation #1:

      $hash{$foo,$bar}

      does not work the same as

      $hash{  @mykeys{'foo','bar'}  } I'll post an additional reply if i can't get the rest of it working...
Re: Tied Hash to emulate double-key hash only accepts one key
by Masem (Monsignor) on Jun 21, 2001 at 21:29 UTC
    (Apparently, my original reply to this got lost in today's site crash...)

    I don't think you need to use anything special like a tie or otherwise for this. The hash key can be an array (not an arrayref), which you can use to emulate multi-key'd hashes without the need for any special coding. See my node An interesting oddity with hashes for more details.

    my %hash; $hash{ 3,4 } = "array"; $hash{ 3 } = "three"; $hash{ 4 } = "four"; # no collisions!

    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
      A neat trick to be sure. However I need it so that $hash{3,4} and $hash{4,3} result in pulling the same value.