Friday, May 2, 2008

Perl: Customize sorting with array


Share at Facebook

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.
#!/usr/bin/perl

use strict;

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

# Student's list, [Age-name-dept]
my @lists = (
"16-alex-120",
"17-john-80",
"18-blek-71",
"16-marsh-71",
"19-abon-80",
"18-marsh-80",
"18-hamilton-80"
);

## 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:
16-marsh-71
16-alex-120
17-john-80
18-blek-71
18-marsh-80
18-hamilton-80
19-abon-80




1 comment:

Anonymous said...

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