Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Adding additional values to a hash of an hash ?

by gnangia (Scribe)
on Nov 12, 2002 at 19:31 UTC ( [id://212370]=perlquestion: print w/replies, xml ) Need Help??

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

I am trying to add additional values to a hash with the same key where the value is basically another hash. For example if I have $hash{'one'} = ('key1'=>'value2'); at one place and I need to add something to it..for example $hash{'one'} = ('key2' => 'value2'); so that the final result looks like this  $hash{'one'} = ('key1'=>'value1','key2'=>'value2');, how would I do it ?
Thanks.

Replies are listed 'Best First'.
Re: Adding additional values to a hash of an hash ?
by Ovid (Cardinal) on Nov 12, 2002 at 19:49 UTC

    The easy method of doing this is as follows:

    my %newhash = ( %hash1, %hash2 );

    However, the above assumes that you do not have duplicate keys in your hashes as keys in hash 2 will overwrite those in hash 1. If you do have duplicate keys, you'll have to figure out what to do and compensate for that.

    Alternatively, if you simply have another key/value pair to add to an existing hash, you can just assign them directly.

    $hash{ $key } = $value;

    Again, this assumes that $key does not already exist.

    Cheers,
    Ovid

    New address of my CGI Course.
    Silence is Evil

Re: Adding additional values to a hash of an hash ?
by pg (Canon) on Nov 12, 2002 at 20:31 UTC
    Checking whether the main key exists, otherwise, you would end up with overwrite all sub_keys under the same main_key.
    use strict; sub put { my ($hash_ref, $main_key, $sub_key, $value) = @_; if (!exists($hash_ref->{$main_key})) { $hash_ref->{$main_key} = {}; } $hash_ref->{$main_key}->{$sub_key} = $value; } sub display { my $hash_ref = shift; my ($main_key, $sub_key); foreach $main_key (keys %{$hash_ref}) { foreach $sub_key (keys %{$hash_ref->{$main_key}}) { print "{$main_key, $sub_key} = " . $hash_ref->{$main_key}- +>{$sub_key}, "\n"; } } } my $hash_ref = {}; put($hash_ref, "one", "key1", "value1"); put($hash_ref, "one", "key2", "value2"); put($hash_ref, "two", "key1", "value1"); put($hash_ref, "two", "key3", "value3"); display($hash_ref);
      Thank you that worked!!!!
Re: Adding additional values to a hash of an hash ?
by grantm (Parson) on Nov 12, 2002 at 20:14 UTC

    Here's a test script that illustrates one approach:

    #!/usr/bin/perl -w use strict; use Data::Dumper; my %hash; print Dumper(\%hash); $hash{one}->{key1} = 'value1'; $hash{one}->{key2} = 'value2'; print Dumper(\%hash);

    Note, I never actually assigned a value to $hash{one}. When I assigned a value to $hash{one}->{key1}, Perl automatically created the hashref for me before assigning 'value1' to the key 'key1'. This automatic creation of a data structure is called autovivification.

    I like to use arrows to indicate dereferencing, but they are optional (and I think they're going away in Perl 6) so these two lines are equivalent:

    $hash{one}->{key1} = 'value1'; $hash{one}{key1} = 'value1';
Re: Adding additional values to a hash of an hash ?
by Anonymous Monk on Nov 12, 2002 at 20:25 UTC
    try this:
    use strict; sub put { my ($hash_ref, $main_key, $sub_key, $value) = @_; if (!exists($hash_ref->{$main_key})) { $hash_ref->{$main_key} = {}; } $hash_ref->{$main_key}->{$sub_key} = $value; } sub display { my $hash_ref = shift; my ($main_key, $sub_key); foreach $main_key (keys %{$hash_ref}) { foreach $sub_key (keys %{$hash_ref->{$main_key}}) { print "{$main_key, $sub_key} = " . $hash_ref->{$main_key}- +>{$sub_key}, "\n"; } } } my $hash_ref = {}; put($hash_ref, "one", "key1", "value1"); put($hash_ref, "one", "key2", "value2"); put($hash_ref, "two", "key1", "value1"); put($hash_ref, "two", "key3", "value3"); display($hash_ref);
Re: Adding additional values to a hash of an hash ?
by hiseldl (Priest) on Nov 12, 2002 at 19:53 UTC
    If $hash{'one'} is a hashref, here is one way to do it:
    my $hashref = $hash{'one'}; $hashref->{'key1'} = 'value1'; $hashref->{'key2'} = 'value2'; print $_,"=",$hashref->{$_},"\n" foreach keys %$hashref;

    --
    hiseldl
    What time is it? It's Camel Time!

      Unfotunately it won't work for me. I saw some code pasted on one of the posts as follows
      push (@{$data{$formname}}, { 'type' => "select", 'field_name' => $selectname, 'value' => $attr->{'value'}

      This would work for me but I don't know how to access the information. It seems like its being pushed into an array where the arrayname is the hash{key} ? How would one access this info? If I can get the answer to this, then I believe I am all set.

        What you're talking about then is a hash of arrays of hashes. $data{$formname} now returns a reference to the array, and to access an individual hash table in the array you can say something like: $data{$formname}->[0]{type}. Basically, what you're doing is a hash lookup to grab the array reference pointed to by $formname, then using an array index to obtain a reference to the nested hash whose data you need to access, and then doing a normal hash lookup there on 'type'.

        Hi gnangia,

        the code above uses a hash slice (hence the @) to assign a value to the key $formname. The value happens to be an anonymous hash, with keys 'type', 'field_name' and 'value', and corresponding values. What happens is that a reference to said anonymous hash is pushed onto the hash slice. To access fields in this anon hash, use code such as:

        $data{$formname}->{'type'};
        or:
        $data{$formname}{'type'};
        Note that the above is untested and may not work (particularly the top example might need some more curlies).

        Update: Never mind my rambling, I missed a pair of parentheses in your code. fever is correct in what the code is and how you access fields in it. I really must get some more sleep, or less cafeine, or both. I thought pushing stuff onto a hash slice sounded weird when I wrote it :)

        CU
        Robartes-

Re: Adding additional values to a hash of an hash ?
by Theseus (Pilgrim) on Nov 12, 2002 at 20:24 UTC
    If you have the hash, and you're only trying to add values to it whenever necessary(not merge it with another hash), you can access it just like this:
    $hash{'one'}{'key2'} = "value2";
    This sets the key "key2" in the second(embedded) hash to "value2".

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-24 04:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found