rosalindwills has asked for the wisdom of the Perl Monks concerning the following question:
Hello; hoping someone can help me because i'm somewhat puzzled...I'm a relative Perl newbie...
I have a multidimensional array which is pulling arrays of three elements from a file that is a list of three-number lines.
In other words, I'm taking a file that looks like:
1 2 20 2 3 15 3 4 3 4 5 17 5 6 28 6 1 23 1 7 1 2 7 4 3 7 9 4 7 16 5 7 25 6 7 36
And producing an array structured like:
my @item_array = {{1, 2, 20}, {2, 3, 15}, {3,4,3}, {4, 5, 17}, {5,6,28}, {6,1,23}, {1, 7, 1}, {2, 7, 4}, {3, 7, 9,}, {4, 7, 16}, {5, 7, 25}, {6, 7, 36}};All of this is written and works. I'd now like to sort @item_array by the third element in each sub array (i.e. {2, 3, 15} should come before {1, 2, 20}, etc.).
I found code which I think should do this:
my @sorted_array = sort { $a->[2] <=> $b->[2] } @item_array;However, when I print this out, it seems that all it's doing is turning all of the sub arrays into the last sub array. In other words, @sorted_array is just twelve instances of {6, 7, 36}.
Does anyone have any idea why this is happening? What would the proper code be to sort this array by the third element of each child array?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Sort multidimensional array by third item
by kennethk (Abbot) on Nov 12, 2010 at 17:17 UTC | |
|
Re: Sort multidimensional array by third item
by choroba (Cardinal) on Nov 12, 2010 at 17:22 UTC | |
|
Re: Sort multidimensional array by third item
by rosalindwills (Initiate) on Nov 12, 2010 at 20:28 UTC | |
by kennethk (Abbot) on Nov 12, 2010 at 20:48 UTC | |
by Tux (Canon) on Nov 12, 2010 at 20:37 UTC | |
|
Re: Sort multidimensional array by third item
by rosalindwills (Initiate) on Nov 12, 2010 at 21:16 UTC | |
|
Re: Sort multidimensional array by third item
by 7stud (Deacon) on Nov 12, 2010 at 22:30 UTC | |
by kennethk (Abbot) on Nov 12, 2010 at 22:42 UTC | |
by 7stud (Deacon) on Nov 12, 2010 at 22:55 UTC | |
by kennethk (Abbot) on Nov 12, 2010 at 22:59 UTC | |
|