If you want to sort your data numerically, then the data must look like a 
number. Your data is mixed numerical and alpha data, hence the error message. 
You first need to extract the numerical parts of your data records and compare 
just those parts.

The first step would be to write a sort routine that extracts the numerical 
parts of the two key variables $a and $b, e.g., $anum and $bnum, and returns 
the value of the expression $anum <=> $bnum ( or $bnum <=> $anum if you want to 
reverse the order). 

That is not the most efficient way to solve this problem, as you are extracting 
the numerical parts more often than necessary, but it is a start. Try that and 
let us know if you want more help.

Once you get that working, you can write a Schwartzian transform that will 
extract the numerical values only once for each record.

> On Jun 17, 2016, at 2:41 PM, Kenneth Wolcott <kennethwolc...@gmail.com> wrote:
> 
> On Fri, Jun 17, 2016 at 2:33 PM, Kenneth Wolcott
> <kennethwolc...@gmail.com> wrote:
>> Hi;
>> 
>>  I'm having trouble understanding the built-in Perl sort with regards
>> to mixed numbers and strings
>> 
>>  I'm looking at http://perldoc.perl.org/functions/sort.html
>> 
>>  I have an array that I want to have sorted numerically and descending.
>> 
>>  The array is composed of elements that look like the following regex:
>> 
>>  ^\d+\t\[a-zA-Z0-9]+$
>> 
>>  I always have "use strict" at the top of my Perl scripts.
>> 
>>  If I try:
>> 
>>    my @articles = sort {$b <=> $a} @files;
>> 
>>  I get error(s)/warning(s) that the data is not numeric.
>> 
>>  if I try:
>> 
>>  my @articles = sort {$b cmp $a} @files;
>> 
>>  I will get numbers sorted as letters, not numerically.
>> 
>>  I tried to understand the sort perldoc page further down, but did
>> not grok it at all.
>> 
>>  What I did as a workaround was to implement my own extremely
>> brute-force sort routine, which works, but is very ugly.
>> 
>>  Since I have very few elements (perhaps as many as a couple dozen),
>> the inefficiency is immaterial.
>> 
>>  I'd rather that my code be correct, intuitive and elegant (and efficient).
>> 
>> Thanks,
>> Ken Wolcott
> 
> Addendum:
> 
> It appears that when the sequence of digits is the same length in all
> instances that the data will be sorted correctly, but when the length
> of the sequence of the digits is not the same in the entire data set,
> that is when the sort results will be incorrect.
> 
> My most current data with this reverse character sort mechanism works
> correctly, but I'd like it to work in all cases.
> 
> -- 
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to