in reply to HOH again.. and tr/// and more..

The code below probably satisfies Q1 - it uses sort alfNum to sort the keys for printing (see below for alfNum).

Given the answer to Q1, Q2 it probably moot.

The answer to Q1 is the answer to Q3.

The key is a user provided compare function used by sort. In this case I've provided one called alfNum:

sub alfNum { my ($aAlf, $aNum) = $a =~ /([a-z]+)(\d+)/i; my ($bAlf, $bNum) = $b =~ /([a-z]+)(\d+)/i; return $aAlf cmp $bAlf if $aAlf ne $bAlf; return $aNum <=> $bNum; }

Note that alfNum returns -1 when $a is less than $b, 0 when they are equal, and 1 when $a is greater.

use strict; use warnings; use Data::Dump::Streamer; use strict; use warnings; my %hoh = ( A10 => {bl=>0, ff=>4, gg=>3}, A2 => {cc=>5, dd=>4, ee=>9}, A21 => {cd=>5, de=>4, ef=>9}, B21 => {og=>0, wo=>4, ee=>3}, B3 => {oa=>0, wd=>4, ec=>3}, B2 => {oo=>5, pp=>4, zz=>9}, ); my %alphaKeys; push @{$alphaKeys{(/^([a-z]+)/i)[0]}}, $_ for keys %hoh; keys %hoh; for (sort keys %alphaKeys) { my @lines; for my $key (sort alfNum @{$alphaKeys{$_}}) { my $index = 0; $lines[$index++] .= sprintf "%-20s", $key; my %items = %{$hoh{$key}}; $lines[$index++] .= sprintf "%-20s", "$_=>$items{$_}" for sort + keys %items; } print "$_\n" for @lines; print "\n"; } sub alfNum { my ($aAlf, $aNum) = $a =~ /([a-z]+)(\d+)/i; my ($bAlf, $bNum) = $b =~ /([a-z]+)(\d+)/i; return $aAlf cmp $bAlf if $aAlf ne $bAlf; return $aNum <=> $bNum; }

Prints:

A2 A10 A21 cc=>5 bl=>0 cd=>5 dd=>4 ff=>4 de=>4 ee=>9 gg=>3 ef=>9 B2 B3 B21 oo=>5 ec=>3 ee=>3 pp=>4 oa=>0 og=>0 zz=>9 wd=>4 wo=>4

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: HOH again.. and tr/// and more..
by tamaguchi (Pilgrim) on Mar 07, 2006 at 02:42 UTC
    Thank you very much for your answer Im sure it will help me very much. But I would also like to know a simpler thing: Just how to sort an internal hash of an HOH numericaly, the beta-keys or whatever one should call them. I have looked at some examples but, not found what Im looking for, maybee it is so easy nobody cares to make examples of it.

      As phrased that is a meaningless question. You can access a hash in sorted order by iterating through a sorted list of keys, but the hash itself is unsorted - that's the nature of the beast.

      You can sort an array because each element in the array has a defined position - it's index. But generally that is unimportant for a hash. There are tied hash implementations that allow itteration over the hash keys in sorted order and that may be what you want, but it may not either. At the end of the day the answer depends implicitley on what you are trying to achieve so there is no one answer to "how do I sort a hash?".


      DWIM is Perl's answer to Gödel