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

时间:2012-09-25 20:10:04

标签: perl sorting 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 = @_;
   ...
}

2 个答案:

答案 0 :(得分:5)

非常简单:

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

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

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

答案 1 :(得分:2)

sub string_sort_arrayref_by_second_element {

  my $param = shift;
  @$param = sort { $a->[1] cmp $b->[1] } @$param;

}