Wednesday, March 31, 2010

File to Hash Technique: Multiple values

If you have a file like below
#File test.txt
usa, phili
usa, cali
france, paris
france, marcille
india, delhi
usa, atlanta

Script to do that is below.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my %table = ();

open(FILE, "test.txt") or die("Unable to open manifest due to $!");
while ()
{
chomp;
my ($key, $val) = split /, /;
$table{$key} .= exists $table{$key} ? ",$val" : "$val";
}
close(FILE);
print Dumper(\%table);


Here is the output.

$VAR1 = {
'usa' => ',phili,cali,atlanta',
'france' => ',paris,marcille',
'india' => ',delhi'
};

No comments: