Thursday, March 13, 2014

How can you store contents of config file into a hash-of-array?

my %conf = ();
open (INI, "<config.ini") || die "Can not open - $!" ;
while (my $line = <INI>) {
if (($line=~/^#/) || ($line=~/^;/)) {
#ignore these lines coz they are comments!
}
else {
if($line =~m/^(.*?)=(.*?)$/) {
push @{$conf{NAME}}, $1;
push @{$conf{SIZE}}, $2;
}
}
}
close INI;

# To access each array in hash-of-array
foreach my $key ( keys %conf )  {
    print "$key = @{$conf{$key}}\n";
}

# To access each element in hash-of-array
foreach my $key ( keys %conf )  {
    foreach ( @{$conf{$key}} )  {
        print "$key = $_\n";
    }
}

# To access single element of particular array in hash-of-array
print "${$conf{NAME}}[0]\n";

#config.ini :
# ';' or '#' can be used to comment any pair!
;[ATTRIBUTE=WIDTH]
First Name=15
Last Name=20
Middle Name=10
Member ID=20
SSN=9

No comments :