Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting a hash of arrays

Status
Not open for further replies.

msclare

IS-IT--Management
Aug 27, 2002
1
GB
I am reading in a tab delimited file to a hash of arrays as follows:

open (TESTFILE, "filename");
while (<TESTFILE>) {
chomp;
($cashflows{field0}[$rowcount],
$cashflows{field1}[$rowcount],
$cashflows{field2}[$rowcount]) =
split(/\t/, $_);
$rowcount ++
}

I then want to sort the hash of arrays by field 2. For example the file contains

1234 text ID25
1765 text ID16
8765 text ID19

After sorting I would like to print out the hash of arrays as:

1765 text ID16
8765 text ID19
1234 text ID25

Can anyone advise on the sort technique. I have tried various approaches but cannot get this to work. Many thanks.
 
Perhaps a better data structure would make it easier. I assume you have a good reason for this one, so here is a way to sort it. I use a string comparason (cmp) on field2. This can have undesired results if the ID numbers can be larger than 99 because this type of sort will put ID100 before ID20. If this isn't a danger then you can use the following. It creates an array of index values that get sorted using a Schwartzian transform (the map/sort/map).
Code:
$rowcount = 0;
my @sortidx =
    map { $_->[0] }
    sort { $a->[1] cmp $b->[1] }
    map { [ $rowcount++, $_ ] } @{$cashflows{field2}};

for (@sortidx) {

    print &quot;$cashflows{field0}[$_]\t$cashflows{field1}[$_]\t$cashflows{field2}[$_]\n&quot;;
}

jaa
 
instead of doing a text sort (example: '100' will be considered less than '20'), you can strip out the 'ID' text for the last column of data as you go. Then you can do a sort by value. Maybe someone can help you with the code since I don't have much experience with sorting. I know the types of sorting but am not up on the syntax.

With sorting by value, you don't have to worry about the numbers exceeding 99.
 
Here's one possibility to implement gorgor's suggestion, a slight modification of what i originally posted.
Code:
$rowcount = 0;
my @sortidx =
    map { $_->[0] }
    sort { $a->[1] <=> $b->[1] }
    map { [ $rowcount++, /(\d+)/ ] } @{$cashflows{field2}};

jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top