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

Bob*_*yan 1 sorting perl reference

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

以下是一些生成$ TransRef的代码.它还没有经过测试,可能有一些错误:

# 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 = @_;
   ...
}
Run Code Online (Sandbox Code Playgroud)

yst*_*sth 5

很简单:

sub sort_trans_ref {
    my $transRef = shift;
    @$transRef = sort { $a->[1] cmp $b->[1] } @$transRef;
    return $transRef;
}
Run Code Online (Sandbox Code Playgroud)

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

sub sort_trans_ref {
    my $transRef = shift;
    my @new_transRef = sort { $a->[1] cmp $b->[1] } @$transRef;
    return \@new_transRef;
}
Run Code Online (Sandbox Code Playgroud)