Deano Deano - 7 months ago 19
Perl Question

Config::Simple Perl module loop through hash

I'm using Config::Simple for my App config, I have created

Stats_feeder.cfg
that has a block
[stats_interval]


[stats_interval]
1m = 60
15m = 900


And my perl script
script.pl


my $cfg = new Config::Simple('stats_feeder.cfg') or die Config::Simple->error();

my $hash = $cfg->get_block('stats_interval');


When I run
print Dumper($hash);
I get

# perl stats_feederv2.pl
$VAR1 = {
'1m' => '300',
'15m' => '900',
'60m' => '3600',
'30m' => '1800'
};


I can access values using
$val = $cfg->param('1m');


I'm trying to loop through this hash and print keys and values, I have tried the following:

foreach my $key ( keys %$hash )
{

print "key $key value $hash{$key}\n";

}


I keep getting

Global symbol "%hash" requires explicit package name at stats_feederv2.pl line 42.
Execution of stats_feederv2.pl aborted due to compilation errors.

Answer

$hash{key} syntax that you use for printing the key's value works when you have a named hash: %hash. In your case, you have an anonymous hash, under a hash reference.

To access the key's value in such a case, you should use this syntax: $hash_ref->{key}. Change:

print "key $key value $hash{$key}\n";

To:

print "key $key value $hash->{$key}\n";
Comments