Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Sort hash keys

by kalyanrajsista (Scribe)
on Sep 17, 2010 at 09:48 UTC ( #860457=perlquestion: print w/ replies, xml ) Need Help??
kalyanrajsista has asked for the wisdom of the Perl Monks concerning the following question:

Monks

I'm trying to sort the hash based on their keys and key is inform of some 'UniqueNumber-Sequence'. Here is what I tried.... Output should be like

1035-46 1035-65 1035-2341 1035-2347
#!/usr/bin/perl my %seq = ( '1035-2341', '1', '1035-2347', '1', '1035-65', '1', '1035- +46', '1'); foreach ( sort {$a cmp $b } keys %seq ) { print $_, "\n"; }

Comment on Sort hash keys
Select or Download Code
Re: Sort hash keys
by GrandFather (Cardinal) on Sep 17, 2010 at 10:04 UTC

    On the face of it all you need is a small adjustment to your sort function:

    my %seq = ('1035-2341', '1', '1035-2347', '1', '1035-65', '1', '1035-4 +6', '1'); foreach (sort {length $a <=> length $b || $a cmp $b} keys %seq) { print $_, "\n"; }

    Prints:

    1035-46 1035-65 1035-2341 1035-2347
    True laziness is hard work
Re: Sort hash keys
by johngg (Abbot) on Sep 17, 2010 at 10:32 UTC

    If, on the other hand, both numerical parts of your key are variant then you can split on the hyphen and do numerical sorts on each.

    knoppix@Microknoppix:~$ perl -E ' > my %seq = map { $_ => 1 } qw{ > 1035-2341 > 1047-835 > 1035-2347 > 874-3971 > 1035-65 > 874-70 > 1035-46 > }; > say for > map { $_->[ 0 ] } > sort { $a->[ 1 ] <=> $b->[ 1 ] || $a->[ 2 ] <=> $b->[ 2 ] } > map { [ $_, ( split m{-} ) ] } > keys %seq;' 874-70 874-3971 1035-46 1035-65 1035-2341 1035-2347 1047-835 knoppix@Microknoppix:~$

    I hope this is helpful.

    Cheers,

    JohnGG

      Thanks JohnGG...It worked
Re: Sort hash keys
by JavaFan (Canon) on Sep 20, 2010 at 12:54 UTC
    As expected a ST1 solution was posted. As usual, no GRT2 variant was. Since I think that if the list you're sorting is large enough to benefit from an ST, it'll benefit more from a GRT, here's the GRT variant:
    my @seq = qw[ 1035-2341 1047-835 1035-2347 874-3971 1035-65 874-70 1035-46 ]; say for map {join "-", unpack "nn", $_} sort map {pack "nn", split "-"} @seq;
    Of course, for a 7 element list, neither ST nor GRT gains much benefits.

    1Schwartzian Transform
    2Guttman Rosler Transform

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://860457]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2014-12-20 14:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (96 votes), past polls