I’m having some trouble with subroutines, namely the sort function being used to sort an array of numbers. I know if you use the sort function solely, it sorts using ASCII format, as the book describes this and that sorts in not the desired order. I’m aware and have an understanding of what gets returned by using <=> to compare values, even being introdued to cmp for strings (although I have not used it yet).
What I don’t understand specifically is how it sorts them numerically – that actual process. I understand what is returned, but the book just says it returns -1, 0 and 1 and not how specifically the numbers end up finally sorted to 1 8 24 72 144 288.
My example:
sub sort_by_number {
return $a <=> $b;
}
@myArray = (1,24,8,144,72,288);
foreach(sort sort_by_number(@myArray)) {
print("$_ ");
}
The example I understand fully. It makes perfect sense but I think that’s mainly due to the coding:
#!/usr/bin/perl
print("Please enter your name: ");
$name = <STDIN>;
chomp($name);
print("Please enter your age: ");
$age = <STDIN>;
chomp($age);
print(greeting($name, $age));
sub greeting {
$msg = "Hello $_[0], ";
determine_age($_[1],$msg);
}
sub determine_age {
$num = ($_[0] <=> 18);
if ($num == -1) {
return "$_[1]you are under 18.($_[0])\n";
} elsif ($num == 0) {
return "$_[1]you will be a 19 on your next birthday!\n";
} else {
return "$_[1]you are over 18!($_[0])\n";
}
}
Massively appreciative if someone could clarify.
Your second example doesn’t do any sorting.
To answer “how it sorts them numerically – that actual process?“, Perl internally implements sort using Merge Sort algorithm (was quicksort before Perl 5.6).
The algorithm itself is fairly complicated (See Wiki for details), BUT underneath it ends up comparing 2 numbers and deciding if one is bigger than the other, and performing some action depending on that decision. If you’re curious about details, the algorithm part that needs the comparison is the
if first(left) ≤ first(right)line on the Wiki example.This is where the custom sort subroutine comes in – it answer “which number is bigger” question for the sorting algorithm (or, to be more specific, whether one number is less than or equal than another).
The way this is implemented, Perl’s
sortwill internally call the “comparator” function, and pass it 2 arguments (by aliases$aand$b); and expect the function to return negative, zero or positive if the first is less than, equal or greater than the second one.