testing testing... perl question

Mark Fowler mark at twoshortplanks.com
Mon Aug 13 14:04:30 BST 2007


On 13 Aug 2007, at 11: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

> 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.

Don't do that.

If you don't pass a block (or subroutine name), sort thinks you're  
string sorting:

print sort "Rod", "Jane", "Freddy";
FreddyJaneRod

This:

> perl -e '@a = (1..5); print sort $a <=> $b, @a;'

Run through B::Deparse like so:

perl -MO=Deparse,-p -e '@a = (1..5); print sort $a <=> $b, @a;'

Shows us perl thinks you wrote this:

(@a = (1..5));
print(sort(($a <=> $b), @a));

i.e. sort a six element list, the first of which is the result of "$a  
<=> $b", which apparently is 0, and the contents of @a, which is  
apparenly 1,2,3,4 and 5.

This is not at all what you probably wanted.

Mark.



More information about the london.pm mailing list