Sort is very powerful and customizable. With sort you can create your own sub routine to determine how an array is sorted. Your subroutine will get two elements of your array as $a and $b. Your return code will determine how the array will be sorted.
-1 -- $a comes before $b
0 -- $a and $b are equal
1 -- $b comes before $a
Below is an example of how to sort on two keys:
@a = ( ["oops", 1], ["oops", 0], [ "happy", 2 ], [ "word", 4 ] );
@a = sort my_sort @a;
foreach $ar (@a) {
print "$ar->[0] is $ar->[1]\n"
}
sub my_sort {
# Lets first compare element 0
if ($a->[0] lt $b->[0]){
return -1;
}
if ($a->[0] gt $b->[0]){
return 1;
}
# Element 0 is equal, let now compare element 1
if ($a->[1] < $b->[1]){
return -1;
}
if ($a->[1] > $b->[1]){
return 1;
}
# Both elements are equal
return 0;
}
Note, this code is not necessarily the best way to do this, it is provided to show some theory behind sort.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.