The only reason I'm replying to this node (its a commonly asked question and has been answered many times) is that there is a tendency to go for "cute" solutions that frankly don't generalize well. If we consider your question literally then the code provided by BrowserUk, dave_the_m and sacked all work fine. However if we dare to think outside the box a little and guess that you may want to do this in such a way that you add to the tree each time then their solutions are not viable. They clobber the tree as they build so they are not useful for repeated use on the same tree. Assuming you were looking for such code perhaps the following (not entirely elegant) solution may be more appropriate:
use strict; use warnings; use Data::Dumper; sub add_to_hash { my $hash=my $root=(ref $_[0] ? shift : {}); my $last=pop; for my $key (@_) { $hash=($hash->{$key}||={}); die "Eeek, not a ref!" unless ref $hash; } $hash->{$last}=1; return $root; } my %hash; add_to_hash(\%hash,qw(a b c d)); add_to_hash(\%hash,qw(a c d e)); print Dumper(\%hash);
HTH
First they ignore you, then they laugh at you, then they fight you, then you win.
-- Gandhi
In reply to Re: hash problem
by demerphq
in thread hash problem
by m.y
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |