Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

How do I push new data into an existing hash?

by Anonymous Monk
on May 22, 2000 at 22:56 UTC ( [id://14263]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (hashes)

How do I push new data into an existing hash?

Originally posted as a Categorized Question.

  • Comment on How do I push new data into an existing hash?

Replies are listed 'Best First'.
Re: How do I push new data into an existing hash?
by KM (Priest) on May 22, 2000 at 23:01 UTC
    Simple answer:

    $hash{key} = $val;

    Better answer:

    read perldata (perldoc perldata)

Re: How do I push new data into an existing hash?
by Juerd (Abbot) on Dec 30, 2001 at 01:55 UTC
    To append to one of the values, treat it like any other scalar and use the .= operator: $hash{key} .= 'string'.

    To merge two hashes into a third, use %third = (%first, %second).

    To add a second hash to the first, use @first{keys %second} = values %second (You could use the merging technique, but that's very inefficient).
Re: How do I push new data into an existing hash?
by BeernuT (Pilgrim) on Dec 30, 2001 at 01:50 UTC
    use the '.=' operator
    my $val = " World"; my %hash = (key => "Hello"); $hash{key} .= $val; print "$hash{key}";
    outputs
    'Hello World'

    -bn
Re: How do I push new data into an existing hash?
by bradcathey (Prior) on May 18, 2005 at 12:44 UTC
    And if it is a hash ref, use the arrow operator:
    $hash -> {key} = $val;
Re: How do I push new data into an existing hash?
by merlyn (Sage) on May 22, 2000 at 23:00 UTC
    perldoc perldata
Re: How do I push new data into an existing hash?
by juo (Curate) on Apr 19, 2001 at 13:23 UTC
    I want to add something to an existing key of a hash. $hash{key}=$val; will replace the content of key with a new content $val but will not add $val to the already existing content of key. If I try to use push to add the new value to the exisiting content then perl will give an error message : Type of arg 1 to push must be array (not hash elem.

      Try $hash{$key} .= $val; if $hash{$key} is a (string) scalar, or push @{$hash{$key}}, $val if $hash{$key} is an array reference. See perldoc perlref and perldoc perlreftut for more on how to play with references.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2024-04-16 14:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found