Perl: Merging Hash elements

Refresh

December 2018

Views

323 time

4

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.

2 answers

5
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};
}
10

ETA:

Ах, я думаю , что я неправильно понял вас .. Вы хотели соединить два отдельных значения в хэш. Легко сделать с map:

my %hash3 = map { $hash1{$_} => $hash2{$_} } keys %hash1;
TLP