in reply to Self-Looping over hash - how to remove duplicate

The problem is that, although keys like 1-4 and 4-1 technically mean the same thing in context, as far as Perl is concerned they're different strings, so they're different keys. What you need to do is ensure that your keys are generated consistently.

Your current code doesn't actually work as written as you've cut a few bits out (like the declaration of %hash2), but try this:

Replace the line:
$spair{$si."-".$sn} = $prod;

With:

if ( $si >= $sn ) { $spair{$si."-".$sn} = $prod; } else { $spair{$sn."-".$si} = $prod; }

That ensures that the keys are always created in the same order (i.e. highest value first in this case) - which means that your keys should then map as you're expecting. Running the following complete code should give you want you want:

use strict; use warnings; use Data::Dumper; my %hash2 =( '1' => 2, '3' => 5, '4' => 2,); my %spair = (); my $prod; foreach my $si (keys %hash2) { foreach my $sn (keys %hash2) { if ($si == $sn) { $prod = $hash2{$si}; } else { $prod = $hash2{$si}*$hash2{$sn}; } if ( $si >= $sn ) { $spair{$si."-".$sn} = $prod; } else { $spair{$sn."-".$si} = $prod; } } } print Dumper \%spair;

Produces:

$VAR1 = { '3-1' => '10', '3-3' => 5, '1-1' => 2, '4-1' => '4', '4-3' => '10', '4-4' => 2 };

As always TMTOWTDI and there's almost certainly a more elegant solution but this albeit off-the-cuff should do the job.

Hope this helps.

--- Jay

All code is untested unless otherwise stated.