[Thousand-oaks-pm] Perl hash question

ansok@alumni.caltech.edu ansok at alumni.caltech.edu
Fri Dec 2 10:48:19 PST 2005


No, I don't think he wanted to preserve existing keys in %foo
-- he said "%foo takes %bar values for keys defined in %bar".

If he did, though, the simple way (perhaps not the best for
very large hashes) would be:

%foo = (%bar, %foo);

Instead of your map statement, I might write it as

$foo{$_} = $bar{$_} foreach grep !exists $foo{$_}, keys %bar;

I don't think there's going to be a significant performance
difference between the two, though.

Gary Ansok

Aram Deltac wrote:
> Well, he wanted to preserve any existing keys in %foo, so that would be:
>
> foreach (keys %bar) {
> 	$foo{$_} = $bar{$_}
> 		unless(exists $foo{$_});
> };
>
> Personally I like using map for things like this:
>
> map { $foo{$_}=$bar{$_} unless(exists $foo{$_}) } keys(%bar);
>
> Aran
>
>> -----Original Message-----
>> From: thousand-oaks-pm-bounces+adeltac=valueclick.com at pm.org
>> [mailto:thousand-oaks-pm-bounces+adeltac=valueclick.com at pm.org] On
> Behalf
>> Of Jim Walker
>> Sent: Friday, December 02, 2005 9:49 AM
>> To: thousand-oaks-pm at mail.pm.org
>> Subject: Re: [Thousand-oaks-pm] Perl hash question
>>
>> And, for large hashes,
>>
>> foreach (keys %bar) {$foo{$_} = $bar{$_}};
>>
>> should use less memory.
>> --
>> Jim
>>
>>
>>
>> Gary Ansok wrote:
>>
>> >Robert Hull wrote:
>> >
>> >
>> >
>> >>I'm looking for a succinct way to join two hashes.  What I would
> like
>> is:
>> >>
>> >>%foo .= %bar ;
>> >>
>> >>Where %foo retains it values for keys undefined in %bar
>> >>and
>> >>%foo takes %bar values for keys defined in %bar.
>> >>
>> >>
>> >>
>> >>
>> >I believe that
>> >
>> >%foo = (%foo, %bar);
>> >
>> >will do what you want.
>> >
>> >Gary Ansok
>> >
>> >_______________________________________________
>> >Thousand-oaks-pm mailing list
>> >Thousand-oaks-pm at pm.org
>> >http://mail.pm.org/mailman/listinfo/thousand-oaks-pm
>> >
>> >
>> >
>> >
>> _______________________________________________
>> Thousand-oaks-pm mailing list
>> Thousand-oaks-pm at pm.org
>> http://mail.pm.org/mailman/listinfo/thousand-oaks-pm
>
> _______________________________________________
> Thousand-oaks-pm mailing list
> Thousand-oaks-pm at pm.org
> http://mail.pm.org/mailman/listinfo/thousand-oaks-pm
>



More information about the Thousand-oaks-pm mailing list