Deano Deano - 2 years ago 76
Perl Question

Config::Simple Perl module loop through hash

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

that has a block

1m = 60
15m = 900

And my perl script

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
$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 line 42.
Execution of aborted due to compilation errors.

Answer Source

$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";


print "key $key value $hash->{$key}\n";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download