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.
You are dealing with a hash reference so you need to use $hash->{$key}
An expression like $hash{$key}
is attempting to access an element of hash %hash
, and the error message you are getting is because that hash doesn't exist. $hash
and %hash
are completely unrelated
$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";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.