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;

In reply to Re: Adding multiple items to a hash by markov
in thread Adding multiple items to a hash by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.