Search code examples
arraysperlperl-data-structures

Perl: Sorting 2D array with multiple columns based on a particular column


Pseudo code:

my @unsortedArray = { ["Harry", 10], ["Tim", 8], ["Joe", 3]};
my @sortedArray = ?????

Final sortedArray should be sorted based on col-2 (integers), taking care of the 1-to-1 relationship with the "Name of the person" (col-1). Final result should look like:

sortedArray should be { ["Joe", 3], ["Tim", 8], ["Harry", 10] }; 

Solution

  • You can give a predicate to sort, that is: a function which is evaluated to compare elements of the list.

    my @unsorted = ( ["Harry", 10], ["Tim", 8], ["Joe", 3] );
    
    my @sorted = sort { $a->[1] <=> $b->[1] } @unsorted;
    

    In the predicate (the expression in curly braces), $a and $b are the elements of the outer list which are compared.

    sort is only concerned with one-dimensional lists, so it won't mess with the internal structure of the elements of the outer list. So the relationship between name and number is retained effortlessly.

    Refer to perldoc -f sort and perldoc perlop for more details.