in reply to confused with a hash which contains reversed keys

This may not be as slick as other answers, but I thought I'd offer it. This one is a "fix up" code, as opposed to maintenance code.

#!/usr/bin/perl use warnings; use strict; my %hash = ( AA=>1, AB=>5, AC=>7, AD=>3, AE=>4, BA=>2, BB=>4, BC=>16, BD=>21, ZA=>12, ZB=>1, ZC=>3, ZY=>2, ZZ=>2, ); my %newhash=(); for ( sort keys %hash ) { next if defined $newhash{sym_index($_)}; if ( defined($hash{reverse($_)}) ) { $newhash{sym_index($_)} = $hash{$_} + $hash{reverse ($_)}; } else { $newhash{sym_index($_)} = $hash{$_}; } } for ( sort keys %newhash ) { print $_, " => ", $newhash{$_}, "\n"; } sub sym_index { my $a = shift; return $a if ( $a le reverse( $a ) ); return reverse( $a ); }
And results are:

C:\Code>perl symmetrize.pl AA => 2 AB => 7 AC => 7 AD => 3 AE => 4 AZ => 12 BB => 8 BC => 16 BD => 21 BZ => 1 CZ => 3 YZ => 2 ZZ => 4
Update: cleaner output

Replies are listed 'Best First'.
Re^2: confused with a hash which contains reversed keys
by Anonymous Monk on Dec 04, 2007 at 13:30 UTC
    i think that your code has a bug...
    look carefylly the AA and ZZ these keys have not the correct values(the values are doupled)
      if you use that the code is ok if ( defined($hash{reverse($_)})and $hash{reverse($_)} ne $hash{$_} )