hmm. i just tried it and it worked. I guess it's one of those situations.

thanks
Christopher


John W. Krahn wrote:
> Christopher Yee Mon wrote:
>> I have an array of strings whose members consist of a number followed
>> by a comma followed by a text string
>>
>> e.g.
>> 1,fresh
>> 2,testurl
>>
>> I want to sort by descending numerical order according to the number
>> part so I made this sort subroutine
>>
>> sub by_counter_field {
>>  my($a, $b) = @_;
>>  $a =~ s/^(.*?),.*/$1/g;
>>  $b =~ s/^(.*?),.*/$1/g;
>>
>>  if ($a > $b) { -1 } elsif ($a < $b) { 1 } else { 0 }
>> }
>>
>> and sorted it with
>>  sort by_counter_field @array;
>> and it didn't work.
>
> The subroutine that you provide to sort is a callback subroutine.  In
> other words, you can't pass arguments to it, so the first line of your
> subroutine "my($a, $b) = @_;" is clearing out the data that sort has
> provided for you.
>
>
>> I've also tried replacing
>>  if ($a > $b) { -1 } elsif ($a < $b) { 1 } else { 0 }
>
> Which should be:
>
> if ($a > $b) { return -1 } elsif ($a < $b) { return 1 } else { return 0 }
>
>
>> with
>>  $b <=> $a
>
> This is the preferred way to do it.
>
>
>> and it still didn't work.
>>
>> I also tried this
>>  sort { ($b =~ /(.*?),.*/)[0] <=> ($a =~ /(.*?),.*/)[0] } @array;
>> and it didn't work either.
>
> It works for me:
>
> $ perl -le'
> my @array = ( "1,fresh", "2,testurl" );
> @array = sort { ($b =~ /(.*?),.*/)[0] <=> ($a =~ /(.*?),.*/)[0] } @array;
> print for @array;
> '
> 2,testurl
> 1,fresh
>
>
>
> John


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