perl - Parsing a CSV file and Hashing -


i trying parse csv file read in other zip codes. trying create hash each key zip code , value number appears in file. want print out contents zip code - number. here perl script have far.

use strict; use warnings;  %hash = qw (      zipcode count );  $file = $argv[0] or die "need csv file on command line \n";  open(my $data, '<', $file) or die "could not open '$file $!\n"; while (my $line = <$data>) {    chomp $line;    @fields = split "," , $line;    if (exists($hash{$fields[2]})) {         $hash{$fields[1]}++;    }else {         $hash{$fields[1]} = 1;    } }  $key; $value; while (($key, $value) = each(%hash)) {   print "$key - $value\n"; }  exit; 

you don't column zip code in, using third field check existing hash element, , second field increment it.

there no need check whether hash element exists: perl happily create non-existent hash element , increment 1 first time access it.

there no need explicitly open files passed command line parameters: perl open them , read them if use <> operator without file handle.

this reworking of own program may work. assumes zip code in second column of csv. if anywhere else change ++$hash{$fields[1]} appropriately.

use strict; use warnings;  @argv or die "need csv file on command line \n";  %counts;  while (my $line = <>) {    chomp $line;    @fields = split /,/, $line;    ++$counts{$fields[1]}; }  while (my ($key, $value) = each %counts) {   print "$key - $value\n"; } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -