Gossamer Forum
Home : General : Perl Programming :

sort array of pipe deliminated data

Quote Reply
sort array of pipe deliminated data
Hi,
I have an array @data that is loaded from a file layed out like so:

Billy Bob|Smith|5|Yes
Jim Steven|Brown|3|Yes
Joe John|Bloggs|4|Yes

my question is how can I sort that array by the number column and return it as an array?

I have figured that
Code:
@sorted_data = sort {$a->[2] <=> $b->[2]} @data;

will sort an array of arrays but that won`t work for this kind of array.
I feel that somewhere in there I should split the data on the pipe but I have tried all sorts of combinations without success.

Any pointers much appreciated.

Cheers

chmod

Last edited by:

chmod: Feb 13, 2003, 6:27 AM
Quote Reply
Re: [chmod] sort array of pipe deliminated data In reply to
Yeah you'll want an array or an arrayref of arrayrefs.

Something like:

Code:
my @rows = ();

open FH, "your file" or die $!;
while (<FH>) {
chomp;
push @rows, [ split /\|/ ];
}
close FH;

my @sorted = sort { $a->[2] <=> $b->[2] } @rows;
Quote Reply
Re: [Paul] sort array of pipe deliminated data In reply to
Thanks Paul,
unfortunately I couldn`t get yours to work.

But this seems to:
Code:
sub do_sort {
# ---------------------------------------------------------
#
my (@data_rows, @sorted_data);

open (DATA, "my.data") or die $!;

while (<DATA>) {
push (@data_rows, $_);
}
close (DATA);

@sorted_data = sort make_sort (@data_rows);

}

sub make_sort {
# ---------------------------------------------------------
#
my ($a) = (split(/\|/, $a))[2];
my ($b) = (split(/\|/, $b))[2];
$a <=> $b;
}

cheers for your help..

chmod

Last edited by:

chmod: Feb 13, 2003, 10:17 AM
Quote Reply
Re: [chmod] sort array of pipe deliminated data In reply to
Strange. I'll try it out in a while and see where I screwed up.
Quote Reply
Re: [chmod] sort array of pipe deliminated data In reply to
It seems my code was ok.

I just tested with:

Hello|Foo|5|Blah
Hello|Foo|2|Blah
Hello|Foo|4|Blah
Hello|Foo|3|Blah
Hello|Foo|1|Blah


...and the output was:

$VAR1 = [
[ 'Hello', 'Foo', '1', 'Blah' ],
[ 'Hello', 'Foo', '2', 'Blah' ],
[ 'Hello', 'Foo', '3', 'Blah' ],
[ 'Hello', 'Foo', '4', 'Blah' ],
[ 'Hello', 'Foo', '5', 'Blah' ]
];