Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Perl Sort on associative arrays

Posted on 2003-11-16
3
Medium Priority
?
1,128 Views
Last Modified: 2008-01-16
Hello,

I want a sort on keys of a associative array. the keys are like 5, 10, 20, 30

I want to show them and the value associated to these keys, but in the ordinal order.
but my sort show: 10 20 30 5

because 1 2 3 5, it sorts this like string, but i want it sorted numericaly!

look at my code:

--------------------------------------------
      my      %liste_sequences = ();
    while( $db->FetchRow() ) {
             %hash = $db->DataHash;
               $liste_sequences{$hash{ordre_affichage}} = $hash{sequence};
      }

      $compteur = 10;
      foreach $ordre_aff (sort(keys(%liste_sequences))) {
                  print "--> $ordre_aff <br>";
        }
---------------------------------------------

Thanx a lot
0
Comment
Question by:uberdruck
  • 2
3 Comments
 
LVL 8

Expert Comment

by:jhurst
ID: 9760844
You will need to create  your own sort function or modify your keys.  Personaly I would do the former.  I would make the keys space filled numbers.
0
 
LVL 11

Accepted Solution

by:
bcladd earned 1000 total points
ID: 9760895
Try the following in your sort loop:

 foreach $ordre_aff (sort {$a <=> $b} (keys(%liste_sequences))) {
               print "--> $ordre_aff <br>";
        }

(from the examples on the perlfunc page for the sort function).

-bcl
0
 
LVL 8

Expert Comment

by:jhurst
ID: 9761262
This is exactly the type of 'your own' sort function that I had in mind, except that you will need to ensure that the sort is a numeric sort and not a text/ascii character sort
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans

926 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question