Perl array multisorting

perl

PHP includes a native function array_multisort. I miss that in Perl. There’s not as many native functions in Perl to work on arrays, so for a critical project I needed to come up with a different solution.

I decided at first to use just one array, for the same purpose.

Let’s say I have the following arrays:

1 – some_string
2 – some_other_string
4 – some_other_random_string
3 – some_other_random_string_again

And I wanted to order them by the first array, with the numbers. Firstly, you need to check that warnings are turned off in Perl, as you’ll often get “warning is numeric” when running your program.

In the end, I created a new array, let’s called it ‘sorted instances’

my @sorted_instances = ();

# When looping through my previous results, push to the new array, where $1 and $2 match the previous two arrays. #
foreach (@unsorted_instances) {
push @sorted_instances, “$1,$2”;
}

Now the magic which sorts the arrays:
@sorted_instances = sort { $a <=> $b } @sorted_instances;

Confirm it works well:
foreach (@sorted_instances) {
print $_;
print “\n”;
}

Messy, but it works.