in reply to Sort array + keep associated indexes in other array
Simple, only sort one thing. Maintaining parallel data structures is a real pain, so don't do that. Instead use either an array of arrays or a hash. Consider:
use strict; use warnings; my @items = (["dog", 20], ["desk", 10], ["cow", 150]); print "By name:\n"; print "$_->[0]: $_->[1]\n" for sort {$a->[0] cmp $b->[0]} @items; print "\nBy weight:\n"; print "$_->[0]: $_->[1]\n" for sort {$a->[1] <=> $b->[1]} @items;
and:
use strict; use warnings; my %items = (dog => 20, desk => 10, cow => 150); print "By name:\n"; print "$_: $items{$_}\n" for sort {$a cmp $b} keys %items; print "\nBy weight:\n"; print "$_: $items{$_}\n" for sort {$items{$a} <=> $items{$b}} keys %it +ems;
Both print:
By name: cow: 150 desk: 10 dog: 20 By weight: desk: 10 dog: 20 cow: 150
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Sort array + keep associated indexes in other array
by johnzzz (Initiate) on Mar 28, 2012 at 09:23 UTC | |
by tobyink (Canon) on Mar 28, 2012 at 10:38 UTC |