Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Adding multiple items to a hash

by markov (Scribe)
on Mar 03, 2004 at 00:17 UTC ( #333415=note: print w/ replies, xml ) Need Help??


in reply to Adding multiple items to a hash

A hash slice is a fast and easy solution, but may need some more explanation than one of the earlier replies.

If you want to insert any hash into another one, you can produce a new hash with %h = (%h, %y). However, this will first extract all elements from both %y and the existing %h. Then a new hash is built on this list of key-value pairs. Quite expensive!

You can use the straight forward:

while(my($k,$v) = each %y) { $h{$k} = $v; }
which is probably the most memory efficient way.

An other solution is this:

my @pairs = %y; while(@pairs) { my $k = shift @pairs; my $v = shift @pairs; $h{$k} = $v; }
There are cases where this is the easiest solution: when $k or $v need some processing.

However, a nice trick is based on hash slicing combined with the keys and values functions. Keys provides all the names to be added to the new hash, and values all the data. Although you cannot predict the order of the names returned by keys, it is quaranteed to be in the same order as the data produced by values. The result is that the next is working:

@h{ keys %y } = values %y;


Comment on Re: Adding multiple items to a hash
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2014-12-27 00:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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





    Results (176 votes), past polls