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



In reply to Re: hash problem by demerphq
in thread hash problem by m.y

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.