Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: How to get keys on key "keys on reference is experimental"

Tags:

perl

I am looking for a solution to Perl's warning

"keys on reference is experimental at"

I get this from code like this:

foreach my $f (keys($normal{$nuc}{$e})) {#x, y, and z

I found something similar on StackOverflow here:

Perl throws "keys on reference is experimental"

but I don't see how I can apply it in my situation.

How can I get the keys to multiple keyed hashes without throwing this error?

like image 529
con Avatar asked Dec 05 '22 18:12

con


2 Answers

keys %{$normal{$nuc}{$e}}

E.g. dereference it first.

If you had a reference to start off with, you don't need {} E.g.:

my $ref = $normal{$nuc}{$e};
print keys %$ref; 
like image 123
Sobrique Avatar answered Mar 03 '23 00:03

Sobrique


The problem is that $normal{$nuc}{$e} is a hash reference, and keys will officially only accept a hash. The solution is simple—you must dereference the reference—and you can get around this by writing

for my $f ( keys %{ $normal{$nuc}{$e} } ) { ... }

but it may be wiser to extract the hash reference into an intermediate variable. This will make your code much clearer, like so

my $hr = $normal{$nuc}{$e};

for my $f ( keys %$hr ) { ... }

I would encourage you to write more meaningful variable names. $f and $e may tell you a lot while you're writing it, but it is sure to cause others problems, and it may even come back to hit you a year or two down the line

Likewise, I am sure that there is a better identifier than $hr, but I don't know the meaning of the various levels of your data structure so I couldn't do any better. Please call it something that's relevant to the data that it points to

like image 35
Borodin Avatar answered Mar 02 '23 23:03

Borodin