[Phoenix-pm] Multi-level hash - quick key reference?

Brock awwaiid at thelackthereof.org
Wed Jun 7 12:52:12 PDT 2006

Heres a couple ideas. One, you could just flatten your hash -- use

  $hash->{1.2.3} = "Hello World";
  $hash->{} = "the quick brown fox";

but, failing that,

use strict;
my $hash = {};
my $str = ".1.2.3\tHello World";
my ($nums,$text) = split /\t/,$str;
my @indexes = split /\./, $nums;
shift @indexes; # Get rid of the first ""
my $cur = $hash;
while(@indexes) {
  my $index = shift @indexes;
  if(!@indexes) { # this is the last one
    $cur->{$index} = $text;
  } else {
    # We might need to vivify
    $cur->{$index} = {} unless defined $cur->{$index};
    $cur = $cur->{$index};
use Data::Dumper;
print "Result: " . Dumper($hash) . "\n";

might help. Simplification, anyone? I suppose you could use evil, er,


On 2006., Metz, Bobby W, WWCS wrote:
| All,
| 	I'm looking for a quicker method of accessing elements in a multi-level hash.  For example, the hash will have values like so
| $hash{1}{2}{3} = "Hello World";
| $hash{1}{3}{4}{5} = "the quick brown fox";
| The input to the program comes from another I can't control which will ouput values like so:
| .1.2.3<tab>Hello World
| .<tab>the quick brown fox
| Parsing the values is cake, but what I'm looking for is a faster way to get values in/out of the hash using the ".1.2.3".  Is there some method that allows for arbitrary hash levels without coding using for loops?  I mean clearly recursion would solve this but I was hoping there was something more simple.  Or is recursion the only answer.  I was hoping for something like this, but I know this example doesn't work.  I've searched for a bit but I must be asking the right questions of mighty google.
| $index = ".1.2.3";
| $index =~ s/^\.//g;
| $index =~ s/\./}{/g;
| print $hash{$index} . "\n";
| Thoughts?
| Thanks,
| Bobby
| _______________________________________________
| Phoenix-pm mailing list
| Phoenix-pm at pm.org
| http://mail.pm.org/mailman/listinfo/phoenix-pm

More information about the Phoenix-pm mailing list