
niall_heavey
Novice
Jul 14, 2010, 7:27 AM
Post #1 of 22
(791 views)
|
|
Sorting hash by value
|
Can't Post
|
|
Hi all, i've been trying to find this on another forum but no joy so thought i'd see what else is out there. I'm quite new to perl so bare with me! I have got a csv file which I am reading in, there is a lot of repeated information in columns 3 and 5. I was trying to see which is the most common entry from both of these columns. I then wanted to sort it in numerical order. At the moment I have my list of the number of entries for each value from both columns but now I am trying to sort it numerically....... (If possible just the top 5 or 10 entries as there are hundreds!) I have searched many tutorial websites and have seen the same piece of code to do this, but for some reason it does not work for me.
#!/usr/bin/perl #use strict; #use warnings; #use Text::CSV; my $dat_file = 'file.csv'; my $index = {}; my $index_test = {}; @data =('col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7'); open (F, $dat_file), print "File Opened\n\n" || die ("Could not open file"); while ($line = <F>) { ($data1,$data2,$data3,$data4,$data5,$data6) = split ',', $line; if (exists($index{$data3})) { $index->{ $data3 } = 1; } else { $index->{ $data3 } =$index->{ $data3 }+1 ; } if (exists($index{$data5})) { $index->{ $data5 } = 1; } else { $index->{ $data5 } = $index->{ $data5 }+1 ; } } foreach $value (sort {$index{$a} cmp $index{$b} } keys %index) { print "$value => $index{$value}\n"; } close (F); print"\n"; This is the code I have, pretty sure the problem is somewhere in the foreach $value (sort {$index{$a} cmp $index{$b} } section near the end. I am not getting an error but am just getting "File Opened " output to the screen! Can anyone see where my problem might be? Thanks, N
|