in reply to Array Sorting
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.
|
|---|