in reply to Re: Classic Sort Algorithm
in thread Classic Sort Algorithm

This node falls below the community's threshold of quality. You may see it by logging in.

Replies are listed 'Best First'.
Re^3: Classic Sort Algorithm
by mr_mischief (Monsignor) on Jun 20, 2011 at 23:14 UTC

    This in part depends on what you mean by "text file". Are you using a text file with one or more white space characters between fields, a colon delimited file (or some variation), or a full-blown CSV file?

    Something as simple as split may work for you. You may want to look at Text::CSV or even something like DBD::Any.

Re^3: Classic Sort Algorithm
by runrig (Abbot) on Jun 21, 2011 at 00:20 UTC
    Did you need help with sorting, or with how to open, read, and parse a file?
Re^3: Classic Sort Algorithm
by 7stud (Deacon) on Jun 21, 2011 at 00:16 UTC
    use strict; use warnings; use 5.010; my $data =<<"END_OF_DATA"; 1.000 64.103 2840.0 1.000 42.735 2840.0 1.000 32.051 2840.0 1.050 64.103 3280.0 1.050 42.735 3280.0 1.050 32.051 3280.0 1.100 64.103 3720.0 1.100 42.735 3720.0 1.100 32.051 3720.0 END_OF_DATA say $data; --output:-- 1.000 64.103 2840.0 1.000 42.735 2840.0 1.000 32.051 2840.0 1.050 64.103 3280.0 1.050 42.735 3280.0 1.050 32.051 3280.0 1.100 64.103 3720.0 1.100 42.735 3720.0 1.100 32.051 3720.0 my @lines; #OPEN YOUR FILE HERE: open my $INFILE, '<', \$data or die "Couldn't open string for reading: $!"; #What I did was I opened the string $data as if it were a file. #Now I can treat $INFILE as if it were a file... for my $line (<$INFILE>) { chomp $line; if($line) { push @lines, [split ' ', $line]; } } use Data::Dumper; say Dumper(\@lines); --output:-- $VAR1 = [ [ '1.000', '64.103', '2840.0' ], [ '1.000', '42.735', '2840.0' ], [ '1.000', '32.051', '2840.0' ], [ '1.050', '64.103', '3280.0' ], [ '1.050', '42.735', '3280.0' ], [ '1.050', '32.051', '3280.0' ], [ '1.100', '64.103', '3720.0' ], [ '1.100', '42.735', '3720.0' ], [ '1.100', '32.051', '3720.0' ] ]; my @sorted = sort{ $a->[1] <=> $b->[1] or $a->[0] <=> $b->[0]} @lines; say Dumper(\@sorted); --output:-- $VAR1 = [ [ '1.000', '32.051', '2840.0' ], [ '1.050', '32.051', '3280.0' ], [ '1.100', '32.051', '3720.0' ], [ '1.000', '42.735', '2840.0' ], [ '1.050', '42.735', '3280.0' ], [ '1.100', '42.735', '3720.0' ], [ '1.000', '64.103', '2840.0' ], [ '1.050', '64.103', '3280.0' ], [ '1.100', '64.103', '3720.0' ] ]; my @results = map {my @arr = @$_; join ' ', @arr} @sorted; say Dumper(\@results); --output:-- $VAR1 = [ '1.000 32.051 2840.0', '1.050 32.051 3280.0', '1.100 32.051 3720.0', '1.000 42.735 2840.0', '1.050 42.735 3280.0', '1.100 42.735 3720.0', '1.000 64.103 2840.0', '1.050 64.103 3280.0', '1.100 64.103 3720.0' ]; for (@results) { say; } --output:-- 1.000 32.051 2840.0 1.050 32.051 3280.0 1.100 32.051 3720.0 1.000 42.735 2840.0 1.050 42.735 3280.0 1.100 42.735 3720.0 1.000 64.103 2840.0 1.050 64.103 3280.0 1.100 64.103 3720.0