
DrZed
User
Jun 4, 2000, 3:34 PM
Post #2 of 6
(241 views)
|
Sure. How are your strings stored? Anyway, here are all sorts of ways to sort: If you have an array of strings: @colors = ("red", "blue", "white", "black", "green"); @sorted = sort @colors; #Now, @sorted is a sorted versions of @colors Note that capitals precede lowercase and numbers would not sort properly (e.g. 100 would come before 20). However, sort supports the passing of a subroutine to customize how it sorts. Here's a program that sorts numbers: #!/usr/bin/perl -w @prices = (99,10000,209,21,901); sub numerically { $a <=> $b } @sorted = sort numerically @prices; # @sorted is now a 'numerically' sorted copy of @prices Ok, there are a few things you need to know. One, sort passes values to be tested to the routine as $a and $b (not as part of @_). Therefore, the routine needs to compare $a and $b and return a value based on their relative order. If $a should appear before $b, the routine should return a negative value. If $b should be before $a, then it should return a positive value. If it doesn't matter, then it should return 0. Ok, now what's with the $a <=> $b? Well, the <=> operator compares two numbers and returns either 1, 0 or -1 depending on if the first value is greater, equal or lesser. It could just as well have been: sub numerically { $a-$b } You can use cmp instead of <=> for sorting text. For example: sub alphabetically { $a cmp $b } Or, if you want to ignore case.... sub alphabetically { lc($a) cmp lc($b) } That's fine for arrays. However, if you want to sort a hash (well, not sort it, but access it as if it were sorted), you can use the following: to access the keys in alphabetical order: foreach $key (sort keys %hash) { print $key; } to access the values in alphabetical order: foreach $key (sort byvalue keys %hash) { print $key; } Enjoy, Dr. Zed
|