JanLaloux has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I have a list of references to "records" that has to be sorted based on one of the fields of the record. I use the following sort code (in the example I use records with only one field):

use strict; my $rRecord; my @List; my @SortedList; $rRecord = [12]; push(@List, $rRecord); $rRecord = [3]; push(@List, $rRecord); $rRecord = [9]; push(@List, $rRecord); $rRecord = [1]; push(@List, $rRecord); @SortedList = sort { $List[$a][0] <=> $List[$b][0] } @List; my $Print = ''; for( my $i = 0; $i <= $#SortedList; $i++ ) { $Print .= " $SortedList[$i][0]"; } print "$Print\n";

After executing the sort the data gets messed up, the debugger looses track of it. In my real code it works the first time but executing the same sort twice in a row the debugger hangs on the second sort. Clearly something is wrong but I can't figure it out.

Replies are listed 'Best First'.
Re: sort messes up data
by McA (Priest) on Sep 08, 2014 at 09:06 UTC

    Hi,

    in the sort code block $a and $b are always two elements of the list to sort. So in your case the comparsion should be something like:

    @SortedList = sort { $a->[0] <=> $b->[0] } @List;

    Regards
    McA

      You're quite right, thanks McA!

Re: sort messes up data
by Corion (Patriarch) on Sep 08, 2014 at 09:07 UTC

    I think you're confused about the contents of @List.

    The elements of @List are not indices but references. But in your sort block, you treat them as indices, which Perl will happily do, but which will not yield the result you want. A reference when used as number evaluates roughly to the memory address where the data is stored. Your array indices are not that.

    Maybe you want to use real array indices, or the array elements themselves?

    # Sort by using indices @SortedList = sort { $List[$a][0] <=> $List[$b][0] } 0..$#List; # Sort by using array elements @SortedList = sort { $a->[0] <=> $b->[0] } @List;
Re: sort messes up data
by Anonymous Monk on Sep 08, 2014 at 09:15 UTC

    After executing the sort the data gets messed up, the debugger looses track of it.

    Basic debugging checklist teaches use warnings which warn you

    Use of reference "ARRAY(0x3f9adc)" as array index at - line 12. Use of reference "ARRAY(0x3f9bec)" as array index at - line 12. Use of uninitialized value in numeric comparison (<=>) at - line 12. Use of uninitialized value in numeric comparison (<=>) at - line 12.

    Creating huge arrays can lead to swapping