i can fetch data from a Database with the following perl code:
my %hash = $vars->getVarHash; #load data into a hash
print Dumper(\%hash);
The output of the Dumper looks like this:
$VAR1 = {
'HASH(0x55948e0b06b0)' => undef
};
Now i know that this hash points to a hash of variables, and each of them points to a list of options for each variable (i guess a "hash of hashes"), sth like this:
HASH(0x55948e0b06b0) --> Variable_a --> Option_a_1, Option_a_2 ...
--> Variable_b --> Option_b_1, Option_b_2 ...
--> Variable_c --> ...
How do i correctly dereference this hash so i can get the values of the Variables and each of is Options?
The basic problem is that you can only dereference references. A hash is not a reference, so "dereference a hash" doesn't make sense.
Your dumper output,
$VAR1 = {
'HASH(0x55948e0b06b0)' => undef
};
doesn't show a nested data structure or reference or anything. It's literally a one-element hash whose (single) key is the string "HASH(0x55948e0b06b0)" and whose value is undef. There's nothing you can do with this structure.
What probably happened is that getVarHash returns a reference to a hash (a single value), which (by assigning to a hash) you've implicitly converted to a key whose corresponding value is undef. Hash keys are always strings, so the original reference value was lost.
Perl can tell you about this particular problem. You should always start your Perl files with
use strict;
use warnings;
The warning for this particular mistake is
Reference found where even-sized list expected at foo.pl line 123.
The solution is to store the returned reference in a scalar variable:
my $hash = $vars->getVarHash;
print Dumper($hash);
Then you can use all the usual methods (as described in e.g. perldoc perlreftut) to dereference it and access its contents, such as keys %$hash, $hash->{$key}, etc.
I'm not sure where getVarHash() is defined, but (as others have said) it looks like it returns a hash reference, not a hash as you're assuming.
You could store the returned hash reference in a scalar and use it as a reference:
my $hash = $vars->getVarHash;
print Dumper($hash);
That's probably the best approach, but it has one disadvantage. If you have code that accesses your hash:
say $hash{foo}; # or whatever
Then you'll need to rewrite it to use a hash reference instead:
say $hash->{foo}; # or whatever
An alternative approach is to dereference the value that comes back from the method so that you can use it as a hash.
my %hash = %{ $vars->getVarHash };
That way, the rest of your code will work as expected without making changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With