Perl- Sorting 2d array- code not working!

  • Thread starter Thread starter Bes
  • Start date Start date

Bes

Bes

Soldato
Joined
18 Oct 2002
Posts
7,318
Location
Melbourne
Hi

I am trying to do a sort on a 2d array in perl. I want to sort on the second column (i.e. indexed by 1) and sort the whole array of arrays alphabetically by the string in [1]. So now its like this: (elements split on space)


A fe00m 50 40 <epoch time> C 41 <epoch time>
A fe06m 50 28 <epoch time> C 60 <epoch time>

I want this (just sorting on one column)

A fe00m 50 40 <epoch time> C 41 <epoch time>
A fe06m 50 28 <epoch time> C 60 <epoch time>
A fe14m 50 11 <epoch time> C 55 <epoch time>

This is the code I am trying to use:

@thresharray = sort { $a->[1] cmp $b->[1] } @thresharray;

Any ideas why it seems to not do anything?

Thanks
 
Last edited:
Hi,

Another way of doing this is:

Code:
# First construct 3 arrays.
@mylist=("d","fe00m","e","a");
@mylist2=("d","fe14m","e","a");
@mylist3=("d","fe06m","e","a");

# Build an array containing references to each of these arrays.
@biglist=(\@mylist, \@mylist2, \@mylist3);

# Sort the big array on the first element of each array in the big array.
@biglist = sort {@$a[1] cmp @$b[1] } @biglist;

# Now list each of the arrays out.
foreach $b (@biglist) {
        foreach (@$b) {
                print STDOUT;
        }
        print STDOUT "\n";
}

I've created three arrays and then put references to them in @biglist so this is an array of references to other arrays. The sort line then compares them, dereferencing the arrays in the sort to get to their first element.

Both your variation of the sort and the dereferencing version seem to work for me in the above code.

Only other thing I can think of is a problems with how you build the array of arrays.

Hope that's some help.

Jim
 
Back
Top Bottom