csv to hash data structure conversion using perl
Posted
by
Kavya S
on Stack Overflow
See other posts from Stack Overflow
or by Kavya S
Published on 2012-11-14T16:06:56Z
Indexed on
2012/11/14
17:00 UTC
Read the original article
Hit count: 248
1. Convert a .csv file to perlhash data structure
Format of a .csv file:
sw,s1,s2,s3,s4
ver,v1,v2,v3,v4
msword,v2,v3,v1,v1
paint,v4,v2,v3,v3
outlook,v1,v1,v3,v2
my perl script:
#!/usr/local/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %hash;
open my $fh, '<', 'some_file.csv' or die "Cannot open: $!";
while (my $line = <$fh>) {
$line =~ s/,,/-/; chomp ($line);
my @array = split /,/, $line;
my $key = shift @array;
$hash{$key} = $line; $hash{$key} = \@array;
}
print Dumper(\%hash);
close $fh;
>>perl hash i.e output should look like:
$sw_ver_db = {
s1 => {
msword => {ver => v2},
paint => {ver => v4},
outlook => {ver => v1}, },
s2 => {
msword => {ver => v3},
paint => {ver => v2},
outlook => {ver => v1}, },
s3 => {
msword => {ver =>v1},
paint => {ver =>v3},
outlook => {ver =>v3}, },
s4 => {
msword => {ver =>v1},
paint => {ver =>v3},
outlook => {ver =>v2}, },
};
© Stack Overflow or respective owner