Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a Perl list in an arbitrary order?

Tags:

algorithm

perl

I have a list of strings whose values come from a fixed set. I need to sort this list in an arbitrary order.

The order of the set is specified by another list of all possible strings, sorted in order in an array.

Here is an example:

my @all_possible_strings_in_order = ('name', 'street', 'city','state', 'postalcode');

my @list_that_needs_to_be_sorted = ('city', 'state', 'name');

I am working in perl. I figure my best bet is to automatically create a hash that associates strings with ordinal numbers, and then sort by reference to those ordinal numbers.

There are about 300 possible strings in the set. Typical lists will have 30 strings that need to be sorted. This isn't going to be called in a tight loop, but it can't be slow either. Automatically building the ordinal hash can't be done ahead of time due to the structure of the program.

I'm open for suggestions on better ways to do this. Thanks!

Edit: You guys are awesome. I can't hold my head up any more tonight, but tomorrow morning I'm going to take the time to really understand your suggestions... It's about time I became proficient with map() and grep().

like image 221
NXT Avatar asked Dec 08 '09 02:12

NXT


People also ask

How do I sort numerically in Perl?

Perl has two operators that behave this way: <=> for sorting numbers in ascending numeric order, and cmp for sorting strings in ascending alphabetic order. By default, sort uses cmp -style comparisons.

How does Perl sort work?

The way sort works in Perl is that it goes over every two elements of the original array. In every turn it puts the value from the left side into the variable $a, and the value on the right side in the variable $b. Then it calls a comparison function.

How do I sort a hash value in Perl?

First sort the keys by the associated value. Then get the values (e.g. by using a hash slice). my @keys = sort { $h{$a} <=> $h{$b} } keys(%h); my @vals = @h{@keys}; Or if you have a hash reference.

How do I sort a string in Perl?

Sorting in Perl can be done with the use of a pre-defined function 'sort'. This function uses a quicksort algorithm to sort the array passed to it. Sorting of an array that contains strings in the mixed form i.e. alphanumeric strings can be done in various ways with the use of sort() function.


1 Answers

Set up the association between strings and their respective positions with

# Define your custom order of all possible strings.
my @custom_order = qw/ name street city state postalcode /;

my %order = map +($custom_order[$_] => $_), 0 .. $#custom_order;

Now you can create a comparison function for use with Perl's sort operator:

sub by_order { $order{$a} <=> $order{$b} }

For example:

my @sorted = sort by_order qw/ city state name /;
print "@sorted\n";
# prints: name city state
like image 146
Greg Bacon Avatar answered Oct 06 '22 00:10

Greg Bacon