in reply to confused with a hash which contains reversed keys

The easiest way is to do it correctly from the beginning.

sub get_key { join '', sort $_[0] =~ /./g } my %hash; while (<DATA>) { chomp; $hash{get_key($_)}++; } use Data::Dumper; print(Dumper(\%hash)); __DATA__ AB AB AB AC AC BA BA BA CA
$VAR1 = { 'AC' => 3, 'AB' => 6 };

But the same method will allow you to fix your hash. (Added)

sub get_key { join '', sort $_[0] =~ /./g } my %hash; while (<DATA>) { chomp; $hash{$_}++; } my %fixed; foreach my $key (keys %hash) { my $val = $hash{$key}; $fixed{get_key($key)} += $val; } use Data::Dumper; print(Dumper(\%fixed)); __DATA__ AB AB AB AC AC BA BA BA CA

By the way, this is a moderated site, so your post may not appear instantly. Please don't triple post.

Replies are listed 'Best First'.
Re^2: confused with a hash which contains reversed keys
by Not_a_Number (Prior) on Dec 03, 2007 at 19:24 UTC

    <nitpick>If all of the OP's hash keys consist of two letters, as in the example data, your code works fine. However, nothing in the 'spec' indicates that this condition is always true. What if the hash is like:

    %hash = ( CAB => 31, BAC => 11, ABC => 42, );

    </nitpick>

      At best, it works great for that hash. At worse, you'd have to change the sort criteria.

      sub get_key { my $key1 = $_[0]; my $key2 = reverse $key2; return (sort $key1, $key2)[0]; }

      Either way, the concept I proposed works fine.