[Purdue-pm] How to sort one dimension of a 2d array
Dave Jacoby
jacoby at purdue.edu
Fri Jan 29 08:08:40 PST 2010
So, you're wanting to sort the inner arrays.
my $x = [[7,0,25,10],[0,9,7,12],[3,2,1,0]] ;
say Dumper $x ;
for my $y ( @$x ) {
@$y = sort { $a <=> $b } @$y ;
}
say Dumper $x ;
jacoby at oz:~$ ./test.pl
line 64.
$VAR1 = [
[
7,
0,
25,
10
],
[
0,
9,
7,
12
],
[
3,
2,
1,
0
]
];
$VAR1 = [
[
0,
7,
10,
25
],
[
0,
7,
9,
12
],
[
0,
1,
2,
3
]
];
jacoby at oz:~$
There may be a more clever choice, but that works as I understand you
want it to.
Phillip San Miguel wrote:
> Phillip San Miguel wrote:
>>
>>>
>> That said, the syntax you provide, in practice, does do exactly what I
>> needed...
> Spoke too soon, no that isn't what I meant. Discarding the hash
> part--which isn't the problem. I have a 2D array. If I sort it your way,
> I get:
>
> perl -e '@a=([7,0,25,10],[0,9,7,12],[3,2,1,0]);@sorted=sort {$a->[0] <=>
> $b->[0]} @a ;use Data::Dumper; print Dumper \@a;print Dumper \@sorted;'
>
>
> $VAR1 = [
> [
> 7,
> 0,
> 25,
> 10
> ],
> [
> 0,
> 9,
> 7,
> 12
> ],
> [
> 3,
> 2,
> 1,
> 0
> ]
> ];
> $VAR1 = [
> [
> 0,
> 9,
> 7,
> 12
> ],
> [
> 3,
> 2,
> 1,
> 0
> ],
> [
> 7,
> 0,
> 25,
> 10
> ]
> ];
>
> But what I want is:
> $VAR1 = [
> [
> 0,
> 0,
> 1,
> 0
> ],
> [
> 3,
> 2,
> 7,
> 10
> ],
> [
> 7,
> 9,
> 25,
> 12
> ]
> ];
>
>
> _______________________________________________
> Purdue-pm mailing list
> Purdue-pm at pm.org
> http://mail.pm.org/mailman/listinfo/purdue-pm
--
Dave Jacoby Address: WSLR S049
Genomics Core Programmer Mail: jacoby at purdue.edu
Purdue University Jabber: jacoby at jabber.org
Phone: 765.49.67368
More information about the Purdue-pm
mailing list