Bastian Angerstein <[EMAIL PROTECTED]> wrote:
: 
: I got the following Problem:
: 
: My hashkeys looks like "number:string" .
: 
: For example "10530:fileparameter-sa1"
:             "10529:fileparameter-mv1"
:               "10531:fileparameter-tx4"
: 
: (without the " signs...)
: 
: I would like to sort the hashkeys by the number
: before the doublepoint.
: 
: Any Idea?

    Your keys can be placed into an array using the 'keys'
function (see 'perlfunc'). You can then sort the array.

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my %foo =(
    '10530:fileparameter-sa1' => 'foo',
    '10529:fileparameter-mv1' => 'bar',
    '10531:fileparameter-tx4' => 'baz',
);

my @unordered_keys = keys %foo;

print Dumper [EMAIL PROTECTED];


    One quick method to get a numeric sort is:

my @ordered_keys = sort { $a <=> $b } @unordered_keys;

print Dumper [EMAIL PROTECTED];


    The problem with this approach is the 'numeric' errors:

Argument "10531:fileparameter-tx4" isn't numeric in sort at aa.pl line 17.
Argument "10529:fileparameter-mv1" isn't numeric in sort at aa.pl line 17.
Argument "10530:fileparameter-sa1" isn't numeric in sort at aa.pl line 17.


    A quick solution might be to turn off numeric errors
temporarily:

{
    no warnings 'numeric';
    print Dumper [ sort { $a <=> $b } keys %foo ];
}


    The problem here is when we start editing this in the
future. This approach also relies on the syntax of the keys
remain fairly constant.


    The better solution might involve converting the key to
numeric and doing the sort on that value.

print Dumper [
    sort { ( split /:/, $a )[0] <=> ( split /:/, $b )[0] } keys %foo
    ];


    The problem with this sort is that we are converting the
keys in %foo more than one time each. Think of a hash with a
few hundred thousand keys.

    Here's a solution whose form is named after one of this
lists contributors. It's called the Schwartzian Transform:

print Dumper [
    map     { $_->[0] }
    sort    { $a->[1] <=> $b->[1] }
    map     { [ $_, ( split /:/ )[0] ] }
    keys %foo
    ];

    I leave the explanation up to Randal.

 http://www.stonehenge.com/merlyn/UnixReview/col06.html



HTH,

Charles K. Clarkson
-- 
Head Bottle Washer,
Clarkson Energy Homes, Inc.
Mobile Home Specialists
254 968-8328









 










-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to