FevtheDev
FevtheDev

Reputation: 157

Perl: How do I sort each index of an array containing strings of numbers

I have an array reading numeric values from a text file. Each index of the array contains a string of numbers separated by a space and in random order. How do I sort each index of numbers in numeric order from lowest to highest? This is what I have so far:

print "\n\nNow sorted: \n";
foreach $line(@lines)
{   
chomp($line);
@nums = sort(split (//, $line));
print "$nums"."\n";
}

Upvotes: 2

Views: 130

Answers (1)

Kenosis
Kenosis

Reputation: 6204

Perhaps the following will be helpful:

use strict;
use warnings;

my @lines = <DATA>;

foreach my $line (@lines) {
    my @nums = sort { $a <=> $b } split ' ', $line;
    print "@nums\n";
}

__DATA__
7 2 9 6 4 10
3 6 8 8 10 1
9 4 10 9 2 5
5 0 2 3 7 8

Output:

2 4 6 7 9 10
1 3 6 8 8 10
2 4 5 9 9 10
0 2 3 5 7 8

Note that the above modifies your script just a little. Remember to always use strict; use warnings; Note also the anonymous sub { $a <=> $b } after sort. This is needed to sort numerically. Without it, a string comparison would have been done, and the first printed line would be 10 2 4 6 7 9. It also appears that you were attempting to split on a zero-width match, i.e., split //, $line. The result of this split is a list of single characters which comprised the line--not what you wanted, as you needed to split on spaces. Lastly, you populated @nums and then printed $nums.

Upvotes: 1

Related Questions