testing testing... perl question
Jonathan McKeown
jonathan+londonpm at hst.org.za
Mon Aug 13 12:24:44 BST 2007
On Monday 13 August 2007 12:31, Aidan Samuel wrote:
> Hello everyone, I'm new here.
>
> Is it ok to ask a perl question?
>
> perl -e '@a = (1..5); print sort $a <=> $b, @a;'
> 012345
>
> perl -e '@a = (1..5); print sort {$a <=> $b} @a;'
> 12345
>
> When using map and grep I tend to leave off the curly braces and just
> use a comma, but if I try this with sort, I get these odd results.
It's clearer what's happening when you look at:
perl -le '$, = " "; $b = 12; print sort $a <=> $b, (1,2,10,11,3)'
-1 1 10 11 2 3
sort in this case (and in your first example) doesn't have a block or
subroutine name or reference (the bit in {} in your second example), so it
does the default lexical sort of a six-item list: the value of $a <=> $b
(which is -1 because $a (undef) is less than $b (12)), and the strings 1, 2,
10, 11, and 3.
In your first example $a and $b were both undef so they compared equal, giving
you the zero, and for single digits numeric and lexical sorts give the same
result.
HTH
Jonathan
More information about the london.pm
mailing list