@data = numeric_sorter(2,0, @data); &print; # Print the contents of the array sub print { foreach my $record (@data ) { for my $i (0 .. 4) { print $record->[$i] . " "; } print "\n"; } } # First sort using the 3rd element of the array(port) and if it's the same # sort by looking at the 1st element(time) sub numeric_sorter { my ($field_num, $field_num_secondary, @data) = @_; my @sorted_items = sort { if ($a->[$field_num] != $b->[$field_num]) { $a->[$field_num] <=> $b->[$field_num] } else { $a->[$field_num_secondary] <=> $b->[$field_num_secondary] } } @data; return @sorted_items; } #### BEFORE SORT: col1 col2 col3 col4 col 5 1040564312 z 89 In 258381720 1040564312 z 89 Out 4194077715 1040564322 z 90 Out 4194081727 1040564322 z 90 In 258385268 1040564335 z 94 IN 4194085256 1040564335 z 94 Out 4194085196 DESIRED SORT: (col4) col1 col2 col3 col4 col 5 1040564312 z 89 In 258381720 1040564312 z 89 Out 4194077715 1040564322 z 90 In 258385268 1040564322 z 90 Out 4194081727 1040564335 z 94 IN 4194085256 1040564335 z 94 Out 4194085196