sweetblood has asked for the wisdom of the Perl Monks concerning the following question:
Here’s my code:
sub sort_array_records { # sort_array_records takes a reference to an array such as \@myarr +ay as # the 1st arg followed by a delimeter, a key (numeric index) and a # boolean uniq flag if a unique array is expected in return. # sort_array_records returns the array in list context. If the key + has # an "n" appended to it the sort is done numerically. An example o +f # sort_array_records is: # @uniq_users = sort_array_records (\@passswd, ":", 0, 1); my ($array_2_sort_ref, $delim, $key, $uniq) = @_; my $numeric = 0; my @sorted_array = (); if ($key =~ /\d*n/) { $numeric = 1; $key =~ s/(^\d*)n/$1/; } if ($numeric) { @sorted_array = sort { (split /$delim/, $a)[$key] <=> (split / +$delim/, $b)[$key] } @$array_2_sort_ref; } else { @sorted_array = sort { (split /$delim/, $a)[$key] cmp (split / +$delim/, $b)[$key] } @$array_2_sort_ref; } if ($uniq) { my $prev = lc($sorted_array[$key]); my @uniq_elems = grep( lc((split /$delim/, $_)[$key]) ne $prev + && ($prev = lc((split /$delim/, $_)[$key]), 1), @sorted_array); return @uniq_elems; } else { return @sorted_array; } }
Incidentally, I did not write this sub from scratch but more expanded on ideas I found in the Perl Cookbook ISBN:ISBN 1565922433 and here at Perlmonks.
TIA
Sweetblood
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Improving sorts using ST
by Abigail-II (Bishop) on May 19, 2004 at 19:55 UTC | |
by drewbie (Chaplain) on May 20, 2004 at 17:45 UTC | |
by sweetblood (Prior) on May 20, 2004 at 19:33 UTC | |
by sweetblood (Prior) on May 20, 2004 at 14:57 UTC |