in reply to hash problem

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


---
demerphq

    First they ignore you, then they laugh at you, then they fight you, then you win.
    -- Gandhi


Replies are listed 'Best First'.
Re^2: hash problem
by simonm (Vicar) on Jan 12, 2005 at 20:33 UTC
    Seconded.

    If you'd prefer not to roll your own, I've got a similar function in my Data::DRef module on CPAN:

    use Data::Dref qw( set_value_for_keys ); my %hash; set_value_for_keys( \%hash, 1, qw(a b c d) ); set_value_for_keys( \%hash, 1, qw(a c d e) );

    There's also a corresponding get_value_for_keys function, if needed...