[ Database tutorial | Text databases ]

Sorting records

If the field that you wish to sort by is the first field in the record, you can sort records by simply using the sort function:

@records = sort @records;

This is described in more detail in the section about field order.

However, if you want to sort by one of the other fields in the record, this can be a real hassle. The way around this is to use the Schwartzian transform. That's a fancy manoeuver used for sorting an array by some non-obvious characteristic - in our case, a piece of text that is lodged somewhere in the middle of the array elements.

For example, suppose that you wish to sort a group of records by the Nth data field in the record. You might do something like this:

#  $n is the data field that we want to look at, so
$index = $n-1; # Because array indices start at 0
@sorted = 
  map { $_->[0] } 
  sort { $a->[1] <=> $b->[1] } 
  map { [ $_, (split /$delimiter/, $_)[$index] ] } 
 @data;
OK, so this might look a little bizarre if you are not familiar with the Schwartzian transform. If you are in that boat, I really encourage you to read Joseph Hall's excellent article on the subject, since I really can't say it better than he can.

The (split /$delimiter/, $_)[$index] part just takes the Nth field in the record, so that the sort portion can use that for sorting on. You may need to play with that a little for your specific application. You'll find that this works much faster than other "split and reassemble" techniques that you might try out.

[ Database tutorial | Text databases ]