简体   繁体   中英

Perl: How to get keys on key “keys on reference is experimental”

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?

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

Eg dereference it first.

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

my $ref = $normal{$nuc}{$e};
print keys %$ref; 

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

keys $hash_ref 

is the reason for the warning keys on references is experimental

Solution:

keys %{ $hash_ref }

Reference:

https://www.perl.com/pub/2005/07/14/bestpractices.html/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM