Perl对数组的引用数组进行排序

Perl对数组的引用数组进行排序

本文介绍了Perl对数组的引用数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Perl比较陌生.我有一个名为$ TransRef的数组的引用,该数组包含对数组的引用.我的目标是编写一个将$ TransRef争论作为其唯一参数的子项,并按第二个元素(字符串)对对底层数组的引用进行排序,然后将输出设置回$ TransRef引用.有人可以告诉我如何在Perl中完成此操作吗?

I am relatively new to Perl. I have a reference to an array called $TransRef that contains references to arrays. My goal is to write a sub that takes the $TransRef arguement as its only argument, sorts the references to the underlying array by the 2nd element (a string) and sets the output back to the $TransRef reference. Can someone please show how this can be done in Perl?

这是一些生成$ TransRef的代码.它尚未经过测试,可能存在一些错误:

Here is some code that generates $TransRef. It has not been tested yet and may have some bugs:

# Parse the data and move it into the Transactions container.
for ($Loop = 0; $Loop < 5; $Loop++)
{
   $Line = $LinesInFile[$Loop];
   # Create an array called Fields to hold each field in $Line.
   @Fields = split /$Delimitor/, $Line;
   $TransID = $Fields[2];
   # Save a ref to the fields array in the transaction list.
   $FieldsRef = \@Fields;
   ValidateData($FieldsRef);
   $$TransRef[$Loop] = $FieldsRef;
}
SortByCustID($TransRef);

sub SortByCustID()
{
   # This sub sorts the arrays in $TransRef by the 2nd element, which is the cust #.
   # How to do this?
   my $TransRef = @_;
   ...
}

推荐答案

非常简单:

sub sort_trans_ref {
    my $transRef = shift;
    @$transRef = sort { $a->[1] cmp $b->[1] } @$transRef;
    return $transRef;
}

尽管不修改原始数组对我来说更自然:

though it would be more natural to me to not modify the original array:

sub sort_trans_ref {
    my $transRef = shift;
    my @new_transRef = sort { $a->[1] cmp $b->[1] } @$transRef;
    return \@new_transRef;
}

这篇关于Perl对数组的引用数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:25