Perl: alphabetizing a list of command line arguments

The tutor returns to the perl sort function.

Back in my post on November 27 I introduced a perl program that finds the median of a list of numbers. It depends on perl’s built-in sort function to put the numbers in order.

Not only does perl’s sort work for numbers, but also for words. The syntax for numbers is

sort{$a <=> $b}@array_of_numbers

while the syntax for words (aka strings) is

sort{$a cmp $b}@array_of_strings

The cmp in the strings syntax is itself a built-in function that compares strings.

Here’s a brief program that orders a list of words it receives from the command line:

#!/usr/bin/perl

@array_in_order=sort{$a cmp $b}@ARGV;
print “\n\nHere is your list of words in alphabetical order:\n\n”;
foreach $one(@array_in_order){
print “$one “;
}
print “\n\n”;

Running the program from the terminal, you enter the list of words after the program name with just spaces (not commas) between. Suppose you save the program as

alphasort.txt

and want to run it on the list

apple xylophone holiday beeswax packing

From the proper directory you key in

perl alphasort.txt apple xylophone holiday beeswax packing

then press enter.

I’ll be talking more about the perl sort function, string comparisons, and much else in coming posts. HTH:)

Source:

Robert’s Perl tutorial

McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply