Perl sorting an array of references to arrays

青春壹個敷衍的年華 提交于 2019-12-23 02:46:11

问题


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?

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 = @_;
   ...
}

回答1:


Pretty straightforward:

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;
}



回答2:


sub string_sort_arrayref_by_second_element {

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

}


来源:https://stackoverflow.com/questions/12590318/perl-sorting-an-array-of-references-to-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!