[英]perl sort 2d array with references
I am somewhat new to perl so please bear with me. 我对perl有些新意,所以请耐心等待。 I've exhausted all possible solutions I could find so far. 到目前为止,我已经用尽了所有可能的解决方案。
Let's say I have some hats with some measurements that are filled elsewhere. 假设我有一些帽子,其中一些测量值在其他地方填充。 And I want to sort them based on a certain column. 我想根据某个专栏对它们进行排序。 I try to do this using perl's "sort" but I don't get them to actually sort. 我尝试使用perl的“排序”来做这个,但我不让它们实际排序。 I believe the problem is that I'm confused on references. 我相信问题是我对引用感到困惑。 The code below is what I'm working with at the moment. 下面的代码就是我目前正在使用的代码。
my @hat1 = [3, 4, 5, 6, 7, 8];
my @hat2 = [4, 6, 5, 1, 1, 2];
my @hat3 = [9, 8, 9, 3, 4, 4];
#eventually work with unknown number of hats
my @binToSort = (\@hat1,\@hat2,\@hat3);
my @binSorted = sort { $a->[4] <=> $b->[4] } @binToSort;
for my $ref (@binSorted){
for my $inner (@$ref){
print "@$inner\n";
}
}
As of now it prints out the unsorted array values: 截至目前,它打印出未排序的数组值:
3 4 5 6 7 8
4 6 5 1 1 2
9 8 9 3 4 4
But I want to be able to arrive at: 但我希望能够到达:
4 6 5 1 1 2
9 8 9 3 4 4
3 4 5 6 7 8
I feel like this is a simple problem but I can't figure out the right way to do it. 我觉得这是一个简单的问题,但我无法找到正确的方法。 Any help is much appreciated! 任何帮助深表感谢!
You need: 你需要:
my $hat1 = [ 3, 4, 5, 6, 7, 8 ];
my $hat2 = [ 4, 6, 5, 1, 1, 2 ];
my $hat3 = [ 9, 8, 9, 3, 4, 4 ];
#eventually work with unknown number of hats
my @binToSort = ( $hat1, $hat2, $hat3 );
my @binSorted = sort { $a->[4] <=> $b->[4] } @binToSort;
for my $ref (@binSorted) {
for my $inner ( @{$ref} ) {
print "$inner";
}
print "\n";
}
Or 要么
my @hat1 = ( 3, 4, 5, 6, 7, 8 );
my @hat2 = ( 4, 6, 5, 1, 1, 2 );
my @hat3 = ( 9, 8, 9, 3, 4, 4 );
#eventually work with unknown number of hats
my @binToSort = ( \@hat1, \@hat2, \@hat3 );
my @binSorted = sort { $a->[4] <=> $b->[4] } @binToSort;
for my $ref (@binSorted) {
for my $inner ( @{$ref} ) {
print "$inner";
}
print "\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.