sub sort_array_records { # sort_array_records takes a reference to an array such as \@myarray 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 of # 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; } }