Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Merging Hash elements

I have 2 hashes.

my %hash1 = (
          '1.3.6.1.2.1.7.1.0' => 'switch_stuff1',
          '1.3.6.1.2.1.6.3.0' => 'switch_stuff4',
          '1.3.6.1.2.1.6.5.0' => 'switch_stuff5',
          '1.3.6.1.2.1.7.4.0' => 'switch_stuff2',
          '1.3.6.1.2.1.6.2.0' => 'switch_stuff3'
    );

my %hash2 = (
          '1.3.6.1.2.1.7.1.0' => 125858,
          '1.3.6.1.2.1.6.3.0' => 120000,
          '1.3.6.1.2.1.6.5.0' => 23766,
          '1.3.6.1.2.1.7.4.0' => 115336,
          '1.3.6.1.2.1.6.2.0' => 200
     );

As you can see, the key values for both hashes are the same.

What I need to do is take the values from %hash1 and use them as keys for the %hash2.

Output:

$VAR1 = {
          'switch_stuff1' => 125858,
          'switch_stuff4' => 120000,
          'switch_stuff5' => 23766,
          'switch_stuff2' => 115336,
          'switch_stuff3' => 200
        };

Note: The number of keys/value pairs in both hashes will always be the same.

Alternatively, the only important thing to me about %hash1 are the values.

'switch_stuff1',
'switch_stuff4',
'switch_stuff5',
'switch_stuff2',
'switch_stuff3'

So if merging the hashes in the way I described is not possible, I can instead turn the %hash1 into an array that contains only the values.

Can anybody please help a Perl Newbie out or at least point me in the right direction? Any help would be greatly appreciated.

Thank you.

like image 964
user1300922 Avatar asked Dec 04 '22 16:12

user1300922


2 Answers

ETA:

Ah, I think I misunderstood you.. You wanted to join the two separate values into a hash. Easily done with map:

my %hash3 = map { $hash1{$_} => $hash2{$_} } keys %hash1;
like image 60
TLP Avatar answered Dec 12 '22 02:12

TLP


my $hash1 = {
          '1.3.6.1.2.1.7.1.0' => 'switch_stuff1',
          '1.3.6.1.2.1.6.3.0' => 'switch_stuff4',
          '1.3.6.1.2.1.6.5.0' => 'switch_stuff5',
          '1.3.6.1.2.1.7.4.0' => 'switch_stuff2',
          '1.3.6.1.2.1.6.2.0' => 'switch_stuff3'
};

my $hash2 = {
          '1.3.6.1.2.1.7.1.0' => 125858,
          '1.3.6.1.2.1.6.3.0' => 120000,
          '1.3.6.1.2.1.6.5.0' => 23766,
          '1.3.6.1.2.1.7.4.0' => 115336,
          '1.3.6.1.2.1.6.2.0' => 200
};  

my $hash3 = {}:

foreach $key (keys %$hash1) {
   $hash3->{$hash1->{$key}} = $hash2->{$key};
}
like image 21
Jeff B Avatar answered Dec 12 '22 02:12

Jeff B