in reply to sort an array by an specific element
Here is one approach that may work:
#!/usr/bin/perl -w use strict; my @array = ( [ 1, 'chuck', 'z' ], [ 2, 'paul', 'b' ], [ 3, 'adam', 'c' ], [ 4, 'rob', 'p' ], [ 5, 'julius', 'w' ], [ 6, 'bryan', 't' ] ); foreach my $i ( sort { $a->[1] cmp $b->[1] } @array ) { print join( " - ", @{$i} ), "\n"; }
If it were a numeric comparison, the cmp above would be replaced by the "spaceship operator" ( '<=>' ).
When run, the following results were obtained:
3 - adam - c 6 - bryan - t 1 - chuck - z 5 - julius - w 2 - paul - b 4 - rob - p
Hope that helps.
Update: 05 Feb 2005
Changed variable in loop from $a to $i, to avoid confusion with the variables used by sort.
|
|---|