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

hi monks
i have declared an hash now i want to add keys as well as values dynamically

if(this)
then add key

if(this)
then add value to a key

if(this)
then add another value the same key

in the end the hash may look something like this

my %children = ( 'a' => [ 'b', 'c' ], 'c' => [ 'x' ], 'b' => [ 'x' ], 'x' => [ 'y' ], 'y' => [ 'z' ], 'z' => [ ], );

i am very bad with hashes.
please help

Replies are listed 'Best First'.
Re: hash : how to add values and keys dynamically
by umasuresh (Hermit) on Dec 21, 2011 at 13:14 UTC
    Here is an excellent perldoc tutorial to get started:
    HOH
Re: hash : how to add values and keys dynamically
by zwon (Abbot) on Dec 21, 2011 at 14:01 UTC

    Not sure what do you want but maybe this will help:

    my %hash; for (qw(a b c)) { push @{ $hash{key} }, $_ if 'this'; }
Re: hash : how to add values and keys dynamically
by Anonymous Monk on Dec 21, 2011 at 15:04 UTC
    It might well be much simpler than you think.   Perl has a very cool feature that is known by the fancy-pants term, “auto-vivication,” which basically means that you can create complicated data structures “all at once,” automagically creating the intervening hashes, hash-slots and so on without having to do so pedantically.   You can also do things in one step, e.g. $$myhash{'foo'}++; will automagically create a 'foo' slot, with an initial value of zero (subsequently incremented to 1 as you requested), and “It Just Works.™”   Perl is very much a pragmatic language, built by real-world practitioners (not academics) to earn their daily bread.