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.


In reply to Re: Self-Looping over hash - how to remove duplicate by gothic_mallard
in thread Self-Looping over hash - how to remove duplicate by monkfan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.