Search code examples
perl

Why doesn't Perl sort numbers in numerical order?


I have to write code that takes user input and turns it into an array, then have the largest number multiply everything in the array. When I input any number <=9 the code runs fine. But when I enter anything over 9 the code "drops" it as the largest value, if that makes any sense.

In my code, I sorted the array then had the last value (the largest) multiply the whole array

input numbers (user input): 1 3 5 7 2 4 6 8 10

final (after being sorted and multiplied: 8, 80, 16, 24, 32, 40, 48, 56, 64

You can see that 10 is the largest number (and should be the last because of the sort), but for some reason 10 is pushed to the first position and 8 is made the last/largest value. If I were to add 9 anywhere in the input, 9 would be made the last/largest number instead of 8, as it should.

I even tried this on an online complier and the result was the same

Why is anything greater than 9 doing this? And how do I fix this?

Also, code looks bad because this is my first day touching Perl lol

print("input numbers: ");
$nums = <STDIN>;

@converted = split(' ', $nums); #turned user input into an array

@sorted = sort(@converted);

$multi = @sorted[-1]; #puts the last/largest number of the array in $multi

foreach $x (@sorted){ #loops through the array and multiplies everything by the last/largest value
    $x = $x * $multi
}

print("final: ");
print join(', ', @sorted); #just added commas to make it readable

I know there's an easier way to do this with the min max stuff but it wasn't working when I tried it


Solution

  • sort sorts lexically by default.

    This places ba before i because b comes before i, and
    this places 10 before 9 because 1 comes before 9.

    To sort numerically, use

    my @sorted = sort { $a <=> $b } @unsorted;
    

    or

    use Sort::Key qw( nsort );
    
    my @sorted = nsort @unsorted;