Web Programming -Sorting It Out

Data sorting can be one of the most crucial elements to fast, efficient scripts. The simplest of the sorting routines might use arrays to store the data/list elements. While this method is effective, it is slow and allows little opportunity for creative use of the data. For instance, suppose you wanted to prioritize a list of items based on your need for each item. You need for each item is signified by a number between 1 and 10. If there were 35 things on your list, each having some priority level between 1 and 10, how would you sort them?

my @array = (“some list of 35 items”);
## I would like this list sorted ##

The problem with the above scenario is that their is no way to associate the priority number to each item. The construct that allows us to do this is called an associative array, or hash.

my %hash = (
‘list_item’=>’priority’,

‘list_item2’=>’priority’

);

A hash consists of key,value pairs. With the key, one can access the value. So, now we have found a way to associated the priority with each item.

foreach my $list_item (@array){ $hash{$list_item} =
“priority – between 1 and 10”;

}
Once we have made all the necessary associations in %hash, we can now sort the list by priority.

for each my $key (sort {($hash{$a} $hash{$b})or($hash{$a}
cmp
$hash{$b})}keys %hash){

print “Task # $hash{$key}: $keyn”;

}

We used the perl function “keys” which returns an array (list) of all the keys in the given %hash. By wrapping the sort{} call into the for each statement, the list of keys returned by the function keys will be sorted according to the rules of the sort routine. This particular example is sorting the keys by their associated values.

The lesson here is that while arrays are a reliable data type for storing and handling lists, associative arrays, or hashes allow for greater efficiency while sorting. Happy coding.