testing testing... perl question

Robin Barker Robin.Barker at npl.co.uk
Mon Aug 13 12:28:51 BST 2007


sort is different from map and grep: sort does not allow an expression, only a block (see perldoc -f sort)
 
Please use -w, that would make it clearer what is going on, which is that the sort is not numeric.
 
% perl -we 'use strict; my @x = (9 .. 11); print sort $a <=> $b, @x;'
Name "main::a" used only once: possible typo at -e line 1.
Name "main::b" used only once: possible typo at -e line 1.
Use of uninitialized value in numeric comparison (<=>) at -e line 1.
Use of uninitialized value in numeric comparison (<=>) at -e line 1.
010119
 
% perl -we 'use strict; my @x = (9..11); print sort {$a <=> $b} @x;'
91011

The original example is alphabetically sorting six elements: starting with 0 (arising from undef <=> undef)
 
Robin
________________________________

From: london.pm-bounces at london.pm.org on behalf of Aidan Samuel
Sent: Mon 13/08/2007 11:31
To: London.pm Perl M[ou]ngers
Subject: testing testing... perl question



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.

Thanks!

Aidan.




-------------------------------------------------------------------
This e-mail and any attachments may contain confidential and/or
privileged material; it is for the intended addressee(s) only.
If you are not a named addressee, you must not use, retain or
disclose such information.

NPL Management Ltd cannot guarantee that the e-mail or any
attachments are free from viruses.

NPL Management Ltd. Registered in England and Wales. No: 2937881
Registered Office: Serco House, 16 Bartley Wood Business Park,
                   Hook, Hampshire, United Kingdom  RG27 9UY
-------------------------------------------------------------------


More information about the london.pm mailing list