By default, perl sort function sort list content in alphabet order, with subname specified, you can do more types of content order in perl.

Here just few examples:

1. Sort array in alphabet order

@sorted = sort @unsorted;

Sort array @unsorted to a sorted array @sorted

2. Sort hash in alphabet order

@sortedkeys = sort keys %hash;

As you know hash varible key/value pair not in order at all, @sortedkeys is an sorted array for keys, it's pretty handy when you want print a hash struct in the order of its key. for example:

for $key in (sort keys %hash) {
# what ever
}

3. Sort array in numeric order

Add subname, so it looks like

@sorted = sort {$a <=> $b} @unsorted;

Sort array @unsorted to a numeric sorted array @sorted

4. Sort hash in numeric order

Similarily,

@sortedkeys = sort {$a <=>$b } keys %hash;

5. Sort content in reverse order

In alphatet order

@sorted = sort {$b cmp $a} @unsorted;
@sortedkeys = sort {$b cmp $a} keys %hash;

In numeric order

@sorted = sort {$b <=> $a} @unsorted;
@sortedkeys = sort {$b <=> $a} keys %hash;

6. Sort content in non case sensitive

of course its always in alphatet order

@sorted = sort {fc($a) cmp fc($b)} @unsorted;
@sortedkeys = sort {fc($a) cmp fc($b)} keys %hash;

7. More advanced example

Compare hash in values instead of key

@sortedvals = sort {$hash{$b} cmp $hash{$a}} keys %hash

The example above sort the hash value in reversed order

8. More advanced examples 2, use subroutine

Create a subroutine byvalue

sub byvalue {
$hash{$a} cmp $hash{$b}
}
@sortedvals = sort byvalue %hash

 

Comments powered by CComment