Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Negative number sorting?

by Ineffectual (Scribe)
on Dec 29, 2001 at 01:17 UTC ( [id://134985]=perlquestion: print w/replies, xml ) Need Help??

Ineffectual has asked for the wisdom of the Perl Monks concerning the following question:

Hey monks,

I have an array that has negative numbers in it which I would like to sort ascending, but neither normal sort nor <=> sort seem to have an effect on the array positioning. I'm assuming this is because of the negative numbers involved. Anyone have a different <=> that would be able to sort negative numbers?

my @array = [ -15, 991, -9, 980, 1, 911, 281, 1299, 870, 1205, 1, 1 ]

Thanks!
Ineffectual

Replies are listed 'Best First'.
Re: Negative number sorting?
by grep (Monsignor) on Dec 29, 2001 at 01:27 UTC
    Ineffectual
     [-15, 991, -9, 980, 1, 911, 281, 1299, 870, 1205, 1, 1]; is not array.
    It is array ref. Use () to signify an array.
    #!/usr/bin/perl -w use strict; my @array = (-15,991, -9, 980, 1, 911, 281, 1299, 870, 1205, 1, 1); my @new_array = sort { $a <=> $b } @array; print "@new_array";

    grep
    grep> cd pub grep> more beer
Re: Negative number sorting?
by danger (Priest) on Dec 29, 2001 at 01:27 UTC

    Your array contains but a single element, and that element is an anymonous array (created with square brackets --- perhaps that is a typo when posting your code?). Use parentheses for ordinary list construction and remember that sort() does not sort in-place but instead returns the sorted list:

    my @array = ( -15, 991, -9, 980, 1, 911, 281, 1299, 870, 1205, 1, 1 ); @array = sort { $a <=> $b } @array; print "@array\n"; __END__ -15 -9 1 1 1 281 870 911 980 991 1205 1299
      Ahh, I understand. My problem was with misunderstanding GD::Graph, not the sort. I was using square brackets because that made the GD::Graph module show up correctly, but the sort wouldn't work correctly. Now using "( )" and \@array, which causes it to show up correctly.

      Is there a way to remove duplicate values using sort or would I have to do a loop to remove them?

      Thanks.
      Ineffectual

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://134985]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (7)
As of 2024-04-19 13:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found