Hue-Bond has already pointed out to the problems with your code, and given a working version.

use warnings; use strict; open my $INF, "<", "look.txt" or die "cannot open"; my @look = <$INF>; close($INF); my @out = sort { (split /\|/, $a)[4] <=> (split /\|/, $b)[5] } @look; for my $line (@out) { my @fields = split /\|/, $line; print join(",", @fields[0 .. 4]), "\n"; } __END__
He's also given a faster solution with both ST and GRT. Thus, there's little left for me to do. However, I can't resist giving a solution using a third, possibly faster sort variant.
use warnings; use strict; open my $INF, "<", "look.txt" or die "cannot open"; my @look = <$INF>; close($INF); my @key = map { (split /\|/)[4] } @look; my @out = @look[sort { $key[$a] <=> $key[$b] } 0 .. @look - 1]; for my $line (@out) { my @fields = split /\|/, $line; print join(",", @fields[0 .. 4]), "\n"; } __END__

I'll also show you a ruby solution as a teaser.

#!ruby -w look = File.open("look.txt").readlines; # here I'm inclined to write ' +map' instead of 'readlines' out = look.sort_by {|line| line.split("|")[4] }; out.each {|line| fields = line.split "|"; puts fields[0 .. 4].join(","); } __END__

That's it. You don't have to listen to the community's whining about strictures, or declare variables, nor do you have to learn complicated idioms for efficently sorting by a field, or quote regexp metacharacters if the language can do that for you. :)


In reply to Re: Sorting an array of arrays by field by ambrus
in thread Sorting an array of arrays by field by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.