Bob Bryan
Bob Bryan

Reputation: 3837

Perl sorting an array of references to arrays

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

Upvotes: 2

Views: 4746

Answers (2)

Dondi Michael Stroma
Dondi Michael Stroma

Reputation: 4800

sub string_sort_arrayref_by_second_element {

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

}

Upvotes: 2

ysth
ysth

Reputation: 98398

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

Upvotes: 6

Related Questions