Friday, May 2, 2008

Perl: Customize sorting with array

Perl provides a function sort, using this you can sort the array/list easily. But sometimes you may require to sort based on multiple key. Thats why Perl provides customization to its sort function. Here is a sample code that will sort a student list and display at sorted order. Go through the comments to understand everything.

use strict;

This code will sort the student's list according to age first.
If age goes equal, then will consider the department.
sorting is ascending.

# Student's list, [Age-name-dept]
my @lists = (

## Calling the custom_sort function with sort
@lists = sort custom_sort @lists;

## Output generate
foreach my $entry (@lists){
print $entry. "\n";

## This will customize the funtion.
sub custom_sort{
## $a and #b ar the compare rows,
## which will automatically comes to here
my @a = $a =~ /(\d+)\-.*?\-(\d+)/;
my @b = $b =~ /(\d+)\-.*?\-(\d+)/;
## Sort by age [less/equals/greater/]
$a[0] <=> $b[0] ||
## if age equals, then sort by dept
$a[1] <=> $b[1]
Sample Output to above Code:

1 comment:

Anonymous said...

Very nice. Exactly what I was looking for. Thanks a lot

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...