[英]Sorting an array of array references in Perl
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: 例如,我想将
@array
的以下数组排序为另一个排序后的数组:
632.8 5
422.1 4
768.6 34
This is the end array, @sorted_array
这是结束数组
@sorted_array
422.1 4
632.8 5
768.6 34
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. 但是,我收到一个错误:当尝试取消引用已排序的数组时,
Use of uninitialized value in print at .\\test.pl line 17
。
#!/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;
}
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.