Code:
#!/usr/bin/env perl
sub char_sort {
my %chars = (
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 4,
"e" => 5,
"f" => 6,
"g" => 7,
"h" => 8,
"i" => 9,
"j" => 10,
"k" => 11,
"l" => 12,
"m" => 13,
"n" => 14,
"o" => 15,
"p" => 16,
"q" => 17,
"r" => 18,
"s" => 19,
"t" => 20,
"u" => 21,
"v" => 22,
"w" => 23,
"x" => 24,
"y" => 25,
"z" => 26);
# perl sets $a and $b for the values to compare.
# This function itself uses itself and calls with two parameters
# select which type of call and wich arguments to use
$word_a = (length($_[0])!=0)?$_[0]:$a;
$word_b = (length($_[1])!=0)?$_[1]:$b;
# Get the first chars, which we need to compare
$a1=substr($word_a,0,1);
$b1=substr($word_b,0,1);
# print("A1=$a1 B1=$b1 A=$word_a B=$word_b\n");
# if both args are empty return with equality(0)
return 0 if(length($word_a)==0 and length($word_b)==0);
# if current char is equal, call this function with the substrings beginning at the second char
return char_sort(substr($word_a,1),substr($word_b,1)) if (($chars{$a1} <=> $chars{$b1})==0);
# if current char is different, we're finished now
return $chars{$a1} <=> $chars{$b1};
}
@list = ("my","favorite","animal","book","for","advanced","biologists");
@sorted = sort char_sort @list;
print("\n");
print("*** Unsorted ***\n");
foreach(@list) {
print;
print("\n");
}
print("\n");
print("*** Sorted ***\n");
foreach(@sorted) {
print;
print("\n");
}
print("\n");