in reply to sort hash by value

The function
sub fmt($){ join("", map { sprintf "%05d", $_ } split(/./, shift)); }
should format the oids you have in a form suitable for comparison, as long as no subkey of the oid is longer than 5 digits (adjust it otherwise).

Replies are listed 'Best First'.
Re: Re: sort hash by value
by halley (Prior) on Jul 10, 2003 at 14:59 UTC

    To expand on ant9000's answer, his function will help in making a comparison tag. He's building a string which has all the numbers in fixed-width columns so that the string comparison operator will naturally order according to numerical fields. To use it to sort by those tags, you'd apply the schwartzian transform:

    my @keys_sorted_by_converted_value = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [ $_, fmt($hash{$_}) ] } keys %hash;

    --
    [ e d @ h a l l e y . c c ]

      You're right: reading again my post, I find it quite cryptic myself... sorry.
      The idea is the following:
      @sorted_keys=sort { fmt($hash{$a}->{oid}) <=> fmt($hash{$b}->{oid}) } keys %hash;
      where fmt is defined as above (with the correction in split below, sure!). You can also use cmp instead of <=>, if you wish.
Re: Re: sort hash by value
by Anonymous Monk on Jul 10, 2003 at 15:31 UTC
    Anyidea why tis sub is failing...I'm passing it an oid string like so:
    my $foo = fmt($oid); print "FOO: $foo\n"; sub fmt($){ join("", map { sprintf "%05d", $_ } split(/./, shift)); }
    Thanks!
      Just a wild guess, but I don't think split /./ is going to do what you want. I think you want split /\./ (note the \, escaping the "match anything" .)
      --
      Mike
        Sure, my fault: the split should be on /\./.