Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] }; 
like image 200
Mike Avatar asked Apr 25 '12 14:04

Mike


People also ask

Can you sort a multidimensional array?

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative (string) keys will be maintained, but numeric keys will be re-indexed.

How do I sort an array of elements in Perl?

Perl has a built-in sort() function to sort an array of alphabets and numbers. When an array is passed to the sort() function it returns a sorted array. Sorting of Arrays in Perl can be done in multiple ways: Use of ASCII values to sort an Array.

How do I sort an array of strings in Perl?

Perl has a built-in function called sort that can, unsurprisingly, sort an array. In its most simple form, you just give it an array, and it returns the elements of that array in a sorted order. @sorted = sort @original.

How does Perl sort work?

sort() function in Perl is used to sort a list with or without the use of method of sorting. This method can be specified by the user in the form of subroutines or blocks. If a subroutine or block is not specified then it will follow the default method of sorting.


1 Answers

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.

like image 91
Stefan Majewsky Avatar answered Oct 12 '22 08:10

Stefan Majewsky