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

Is there a function or operator that allows you to -ADD- a new list of key/value pairs to an existing hash ? Something like:
%hash .= (a=>'a', b=>'b');
I realize that I can use:
%hash = (%hash, a=>'a', b=>'b');
but was hoping for something more elegant/efficient.
Thanks !

Replies are listed 'Best First'.
Re: Adding multiple items to a hash
by markov (Scribe) on Mar 03, 2004 at 00:17 UTC

    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;
Re: Adding multiple items to a hash
by Paladin (Vicar) on Mar 02, 2004 at 23:08 UTC
    Use a hash slice:
    @hash{"key1", "key2"} = ("value1", "value2");
Re: Adding multiple items to a hash
by Anonymous Monk on Mar 02, 2004 at 23:55 UTC
    sub hpush (\%@) { my ($hash, %add) = @_; $hash->{$_} = $add{$_} for keys %add; } my %config = ( home => '/home/foo', temp => '/tmp' ); hpush %config, root => '/root', sbin => '/usr/sbin';
      Just for my $.02:
      sub hpush (\%@) { my ($hash, %add) = @_; @{$hash}{keys %add} = values %add; }
      --Stevie-O
      $"=$,,$_=q>|\p4<6 8p<M/_|<('=> .q>.<4-KI<l|2$<6%s!<qn#F<>;$, .=pack'N*',"@{[unpack'C*',$_] }"for split/</;$_=$,,y[A-Z a-z] {}cd;print lc
Re: Adding multiple items to a hash
by Anonymous Monk on Mar 03, 2004 at 17:12 UTC
    $hash{a}='a'; $hash{b}='b';