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.

use strict;
use warnings;
use Data::Dumper;

my %table = ();

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

Here is the output.

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

No comments: