Please, when you post code, surround it with <code> ... my code here ... </code> tags. Otherwise all the formatting gets lost and we can't read with any ease what you wrote.

That being said, it appears that you are confounding two very different meanings for the word "array". In one part of your code, you are viewing the line you read in as an array of comma delimited fields, i.e.  @array=split(/,/ $line). In another part of your code, when you sort, you are viewing the collection of records (one per line) as an array. Perl is confused because the "array" you are sorting to put the records in age order is the array of fields. All you are doing in your sort is sorting the field values within a single record, not the records.

Human beings can handle such ambiguities well, but computer programs are much less tolerant. You can have two meanings of arrays, BUT you must use two different structures for each meaning:

Thus, your code should look something like this.

my @aRecords; my $iRecord=0; while ($line = <INPUT_FILE>) { my @aFields = split(/,/, $line); $aRecords[$iRecord] = \@aFields; # \@ creates an array reference $iRecord++; } # now that you have read in all the lines, you can sort them # assuming age is the second field, it will be stored at # index 1 (fields are numbered starting at 0) my @aSortedRecords = sort { $a->[1] <=> $b->[1] } @aRecords;

You'll need to use an array reference to accomplish this, please take a look at perllol, and possibly perlref and perldsc as well.

Update: expanded explanation of why code doesn't work and clarified description of AoA.


In reply to Re: Array Sorting by ELISHEVA
in thread Array Sorting by sreenath

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.