If you want to keep information around about the original ordering of the array, you'd probably do best to create an auxilliary data structure to retain the information.
@a1 = (33, 11, 22)
@unsorted = ();
foreach ( 0 .. $#a1 ) {
push @unsorted, [ $a1[$_], $_ ];
}
@sorted = sort { $a->[0] <=> $b->[0] } @unsorted;
foreach ( 0 .. $#a1 ) {
($a2[$_], $index[$_]) = @{$sorted[$_]);
}
This puts the sorted data in @a2 and the original index values in @index.
Main Topics
Browse All Topics





by: thoellriPosted on 2003-01-13 at 10:30:44ID: 7719101
I believe you want to know about the 'sort' operator:
1: my @a=(33, 11, 22);
2: my @a2=sort @a;
3: my @a3=($a[1],$a[2],$a[0]);
4: print q{@a is },join(",",@a),qq{\n};
5: print q{@a2 is },join(",",@a2),qq{\n};
6: print q{@a3 is },join(",",@a3),qq{\n};
This script when run, will sort the elements from @a into @a2 (that happens on line 2).
Alternatively you can build a new array from the elements in @a in an order specified by yourself as shown on line 3.
Line 4,5 and 6 just print the contents of the various arrays and the output will be:
@a is 33,11,22
@a2 is 11,22,33
@a3 is 11,22,33
Hope this helps
Tobias