On 7 June 2011 17:48, Brian F. Yulga <byu...@langly.dyndns.org> wrote:
> Leo Lapworth wrote:
>> On 7 June 2011 07:47, Agnello George<agnello.dso...@gmail.com>  wrote:
>>>
>>> I got the following hashref
>>>
>>
>> <snip>
>>
>>>
>>> now i need to push $select_all_website into $selet_domU_data
>>>
>>
>> I think this is what you want...
>>
>> use strict;
>> use warnings;
>>
>> my $hash_ref_1 = {
>>         a =>  1,
>>         b =>  2,
>> };
>>
>> my $hash_ref_2 = {
>>         a =>  3,
>>         c =>  4,
>> };
>>
>> my $new_hash_ref = {
>>         %{$hash_ref_1},
>>         %{$hash_ref_2}
>> };
>>
>> use Data::Dumper;
>> print Dumper($new_hash_ref);
>>
>> Which produces:
>>
>> $VAR1 = {
>>           'c' =>  4,
>>           'a' =>  3,
>>           'b' =>  2
>>         };
>>
>>
>
> You are probably close to what the OP wanted; it is hard to read minds since
> "pushing onto hashes" makes no sense.  I would call it "merging two hashes".
>  For the OP's data maybe this isn't an issue (and hence why you didn't state
> it), but in your sample data, the value for key 'a' in hash_ref_1 is
> overwritten by the value in hash_ref_2 during the merge.  Even though your
> way is short and concise, perhaps it's safer to check each key before
> assignment?  I suppose the decision to check depends on the predictability
> of the source data...
>
> my $combined_hash = { %$hash_ref_1 };
>
> foreach my $key_in_hsh2 ( keys %$hash_ref_2 ) {
>
>    if (exists $hash_ref_1->{$key_in_hsh2} ) {
>        # some algorithm to deal with duplicate keys or alert user
>        warn "found duplicate key '$key_in_hsh2', keeping original value\n";
>
>    } else {
>        $combined_hash->{$key_in_hsh2} = $hash_ref_2->{$key_in_hsh2}
>    }
> }

Hi Brian,

I should have pointed it out (it's why I gave that example), thanks
for the clarification.

Leo

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to