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

O enlightened ones

How do I add an extra key/value pair to an existing hash?
For example, if I have a hash like this:

%hash=(a=>1, b=>2, c=>3)

how do I add on the scalar values d and 4 to get

%hash=(a=>1, b=>2, c=>3, d=>4)?

Can I use push, as for an array?

This is probably a really basic question, but I can't find an answer to it anywhere. The Camel book only seems to give the 'push' commands for arrays, not hashes, and there is nothing listed under 'hash processing' for adding elements. Do I have to turn my hash into an array, push my values, and then turn the array back into a hash again?

Kind regards,

Campbell

Replies are listed 'Best First'.
Re: adding key/value pairs to a hash.
by cbro (Pilgrim) on Jun 20, 2003 at 13:58 UTC
    $key = 'd'; $value = 4; $hash{$key} = $value;

    That's all you need to do.
    Update:
    Just wanted to say that hashes can be used for so many different things, internal (e.g. %ENV, %INC, %main) and external, in perl; you will want to master them. If you're not getting enough from the 'camel' book, try the Black Book and perldoc -q hash.
Re: adding key/value pairs to a hash.
by bobn (Chaplain) on Jun 20, 2003 at 13:59 UTC
    $hash{d} = 4;


    --Bob Niederman, http://bob-n.com
Re: adding key/value pairs to a hash.
by nite_man (Deacon) on Jun 20, 2003 at 13:59 UTC
    $hash{d} = 4; # for hash $hash->{d} = 4; # for hash reference
          
    --------------------------------
    SV* sv_bless(SV* sv, HV* stash);
    
Re: adding key/value pairs to a hash.
by flounder99 (Friar) on Jun 20, 2003 at 16:58 UTC
    You can also add key/value pairs like this:
    %hash=(a=>1, b=>2, c=>3); %hash=(%hash, d=>4, e=>5, f=>6);

    --

    flounder

Re: adding key/value pairs to a hash.
by perlguy (Deacon) on Jun 20, 2003 at 19:59 UTC

    You can also do it using a hash slice, which allows you to define/set values to multiple keys at once. Try the following:

    use Data::Dumper; use strict; my %hash=(a=>1, b=>2, c=>3); @hash{'d', 'e', 'f'} = (4, 5, 6); print Dumper \%hash;
Re: adding key/value pairs to a hash.
by campbell (Beadle) on Jun 20, 2003 at 14:00 UTC
    Thanking you

    Regards

    Campbell