Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

append values to a same key in hash

by shan_emails (Beadle)
on Jul 06, 2009 at 09:18 UTC ( #777494=perlquestion: print w/ replies, xml ) Need Help??
shan_emails has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

Is there any option to append the values of the same key in a hash.

eg.
%h =( aid=>'6077', 6077.1=>{pii=>"aaaa", pit=>"bbbb", doi=>"cccc", }, abc=>'asdf', ); #I need to append values as follows $h{6077.1} = { pii=>"aaaa", pit=>"bbbb", doi=>"cccc", xmltype=>'000', weight=>'111', }

Regards,
Shanmugam A.

Comment on append values to a same key in hash
Download Code
Re: append values to a same key in hash
by targetsmart (Curate) on Jul 06, 2009 at 09:24 UTC
    $h{6077.1}{'xmltype'} = '000'; $h{6077.1}{'weight'} = '111';
    will do it.
    see perldsc


    Vivek
    -- 'I' am not the body, 'I' am the 'soul', which has no beginning or no end, no attachment or no aversion, nothing to attain or lose.
Re: append values to a same key in hash
by jethro (Monsignor) on Jul 06, 2009 at 09:26 UTC
    $h{6077.1}->{xmltype}= '000';

    You don't really append to a hash (since there is no ordered row or queue where you can append behind) but just insert values. To answer your probable next question too, if you want to test if a value already exists in the hash, you can use the function exists()

    if (exists($h{6077.1}->{xmltype}) { ... }

    UPDATE: changed two ] to }, stupid typing error found thanks to AnomalousMonk

      @shan emails,
      you can use hash of hash data structure.
      Thank you,

      it works fine.

      Thanks for your response.

      Just be aware that exists($h{a}->{b}) will autovivify the first hash key component ({a}):

      use strict; use warnings; my %h; unless (exists($h{foo}{bar})) { print "\$h{foo}{bar} exists: no\n"; print "\$h{foo} exists: ", exists($h{foo})?'yes':'no', "\n"; } #outputs # $h{foo}{bar} exists: no # $h{foo} exists: yes

      If you want to be extra careful not to create hash keys, you'll have to use if (exists($h{a} and exists($h{a}->{b}) instead. and (or &&) short circuits so you'll never reach the second test if the first part of the key is non-existent.

      Best, beth

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://777494]
Approved by targetsmart
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (16)
As of 2014-12-18 10:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (49 votes), past polls