2

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";
}
2
  • 1
    Can you show the sample input file content? Commented Nov 20, 2013 at 3:43
  • Aside from "$nums" where I think you want join(' ', @nums), what do you think is wrong with your current code? And as @Guru said, can you share some input? Commented Nov 20, 2013 at 4:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

if you are just feeding a line to split ' ', no need to chomp it - trailing whitespace will be ignored
@ChristopherFevrier: if it worked for you, click on the big checkmark to mark this as an accepted answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.