On Tue, Aug 16, 2011 at 12:04 PM, Matt <lm7...@gmail.com> wrote:
> I believe you can sort an array like so:
>
> sort @my_array;
>
> I need to sort a string though.
>
> I have $a_string that contains:
>
> 4565 line1
> 2345 line2
> 500 line3
> etc.
>
> Obviously \n is at end of every line in the string.  I need it sorted.
>  How would I approach this?

Assuming you want to sort the lines, you could split it into a list,
store the list in an array, sort the array, and the join the array
back into a string:

use strict;
use warnings;

my $foo = <<EOF;
4565 line1
2345 line2
500 line3
EOF

my @bar = split "\n", $foo;

@bar = sort @bar;

$foo = join "\n", @bar;

__END__

Of course, that will use the standard string comparison on the entire
line. If you want to sort by the number in front, for example, then
you'll have to specify the code to sort with:

sub get_baz
{
    my $record = shift;

    return ($record =~ /^([0-9]+)/);
}

@bar = sort { get_baz($a) <=> get_baz($b) } @bar;

__END__

HTH,


-- 
Brandon McCaig <http://www.bamccaig.com/> <bamcc...@gmail.com>
V zrna gur orfg jvgu jung V fnl. Vg qbrfa'g nyjnlf fbhaq gung jnl.
Castopulence Software <http://www.castopulence.org/> <bamcc...@castopulence.org>

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to