views:

93

answers:

3

Hi, I have an array which looks like this:

array[0]: 6 8
array[1]: 12 9 6
array[2]: 33 32 5
array[3]: 8 6

What I want to do is to sort this array that it looks like this:

array[0]: 6 8
array[1]: 6 9 12
array[2]: 5 32 33
array[3]: 6 8

I know I can sort the array with @newarray = sort {$a cmp $b} @array;, but I need to sort the elements in each line as well. How can I do that?

+4  A: 

You have a list of items that you want to transform. That's a perfect candidate for map. Also note the default behavior of split: it operates on $_, splitting on whitespace, after removing leading whitespace.

my @array = ('6 8', '12 9 6', '33 32 5', '8 6');
@array = map { join ' ', sort {$a <=> $b} split } @array;
FM
+6  A: 

Assuming that you have an array of strings there, and that all you want is to sort each string as if it were a sub-array of numbers (but leave it a string?):

#!/usr/bin/env perl
use strict;
use warnings;

my @array = ('6 8', '12 9 6', '33 32 5', '8 6');

foreach my $string (@array) {
    $string = split_sort($string);
}

sub split_sort {
    my $string = shift @_;
    my @internal_nums = split ' ', $string;
    @internal_nums = sort {$a <=> $b} @internal_nums;
    return join ' ', @internal_nums;
}

print "@array\n";
Telemachus
thx. that did it.
+5  A: 

You could also solve it using map

#!/usr/bin/env perl


my @numbers = (
    '6 8',
    '12 9 6',
    '33 32 5',
    '8 6',
);

my @sorted;
push (@sorted, map { join " ", sort { $a <=> $b }  (split / /, $_) } @numbers);


print "$_\n" for @sorted;

outputs:

6 8
6 9 12
5 32 33
6 8
dalton
+1 for a solution that is much shorter, easier to understand and more efficient than a foreach loop with a subroutine call on each iteration.
Jonas
+1 for the same reasons, though it could be shortened considerably: `map { join " ", sort split } @numbers` should work.
Jon Purdy
@Jon Actually, no, that won't work. You still need a numeric sort - `map { join " ", sort {$a <=> $b} split } @numbers`.
Telemachus
@Telemachus: Darn. I guess my Perl is a tad rusty.
Jon Purdy