testing testing... perl question

Jonathan Stowe jns at gellyfish.com
Mon Aug 13 12:50:03 BST 2007

On Mon, 2007-08-13 at 11:31 +0100, Aidan Samuel wrote:
> Hello everyone, I'm new here.
> Is it ok to ask a perl question?

Only if you promise to make some cogent on topic posting later.

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

You'll find that the output of:

  perl -e 'print $a <=> $b'

Will give the clue.

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

Compare the respective signatures for sort, map and grep in the perldoc

All three allow

  <func> BLOCK LIST

whereas only map and grep give

  <func> EXPR, LIST

If you have a comma in the arguments to sort then it is parsed as

  sort LIST

the expression "$a <=> $b" is evaluated before being passed to sort (and
because at this point they are undefined the result of the comparison is
0 ) you are sorting the list 0,1,2,3,4,5.  You can test this further by
assigning values to $a and $b before the sort:

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

And so forth.

This signature kills bloggers

More information about the london.pm mailing list