Quote:
Originally Posted by rohitbasu77
I am little confused what it print for $a and $b, how the comparision is really happening. can you explain.....
#!/usr/bin/perl
@array = qw(7 8 59 58 4 5 6 2 59);
@array2 = sort {$a <=> $b; print "$a and $b.... comp.. \n"; } @array;
print "$_\n" for @array2;
$a and $b are "internal" global perl variables. As mentioned earlier in Kevin's article.
I did not chose those names. When testing for comparison the "block" or function will return one of three values: -1, 0, 1.
example:
-
-
$test = 31;
-
$test2 = 32;
-
-
print $test <=> $test2;
-
The output is: -1.
Here is how I think of it: $test2 must "go back" to reach $test value.
If $test were larger than $test2:
-
-
$test = 40;
-
$test2 = 32;
-
-
print $test <=> $test2;
-
The output is: 1.
Then $test2 must "go forward" to reach $test value. "1"
If they are the same:
-
-
$test = 31;
-
$test2 = 31;
-
-
print $test <=> $test2;
-
The output is: 0.
$test2 doesn't need to go "anywhere" to reach $test value.
{} is known in perl as an anonymous "block".
When using sort the block must return 1, 0, or -1.
You can actually write your own subroutine in that place as long as it returns either 1, 0, or -1. Example:
-
sort sortit @array;
-
-
sub sortit {
-
$a <=> $b
-
}
-
This can be very useful for sorting multilevel arrays and/or hashes.
Here is a sub that will sort a hash, based on it's values, and if two keys have the same value it sorts according to the key.
Let's say you own a department store, and want to keep track of the various departments sales for each month. You would like the departments that earn the most money listed first, and departments that sale the same amount to be alphabetically sorted by name.
-
#!/usr/bin/perl -Tw
-
-
use strict;
-
-
my %sale = ( 'Sound'=> 45,
-
'Lighting'=> 25,
-
'Electronics'=> 89,
-
'Extra'=> 25,
-
'Clothing'=> 45,
-
'Home Goods'=> 67);
-
-
for my $dept ( sort sort_num_name keys %sale){
-
print "$dept sold: \$$sale{$dept}\n";
-
}
-
-
sub sort_num_name {
-
$sale{$b} <=> $sale{$a} ||
-
$a cmp $b;
-
}
-
This will output:
-
Electronics sold: $89
-
Home Goods sold: $67
-
Clothing sold: $45
-
Sound sold: $45
-
Extra sold: $25
-
Lighting sold: $25
-
This is because 0 is false to perl, so when two values are identical they return 0, and then the "||" or statement is executed.
You should never alter the values of $a or $b. You also cannot pass $a and $b into the sub via "$_". As well as you cannot use "next", "last", or recursive subroutines. $a and $b will be set by perl within the lexical scope of the sort function call. (You can use this same sub later to sort another Hash)
Read more here:
Perldoc sort