EarthIsHome
EarthIsHome

Reputation: 735

Sorting an array of array references in Perl

Synopsis

I'm trying to sort an array of array references based on the arrays' second element.

For example, I would like to sort the following arrays, in @array into another, sorted array:

632.8 5
422.1 4
768.6 34

This is the end array, @sorted_array

422.1 4
632.8 5
768.6 34

Attempted Code

I came across this answer and have modified it slightly. However, I receive an error: Use of uninitialized value in print at .\test.pl line 17 when I try to dereference the sorted array.

#!/bin/perl
use strict;
use warnings;

my @array = ();
foreach my $i (0..10) {
    push @array, [rand(1000), int(rand(100))];
}

foreach my $i (@array) {
    print "@$i\n";
}
print "================\n";

my $sorted_ref = sort_arr(\@array);
print @$sorted_ref;

sub sort_arr {
    my @arr = @$_[0];
    my @sorted_arr = sort { $a->[1] cmp $b->[1] } @arr;
    return \@sorted_arr;
}

Upvotes: 0

Views: 366

Answers (1)

AKHolland
AKHolland

Reputation: 4445

You're passing an array reference into the subroutine and then trying to use it as an array. You need to dereference it first.

sub sort_arr {
    my ($arr) = @_;
    my @sorted_arr = sort { $a->[1] cmp $b->[1] } @{ $arr };
    return \@sorted_arr;
}

Upvotes: 5

Related Questions