开发者

How to use foreach with a hash reference?

开发者 https://www.devze.com 2023-02-15 16:19 出处:网络
I have this code foreach my $key (keys %ad_grp) { # Do something } which works. How would the same look like, if I don\'t have %ad_grp, but a reference, $ad_grp_re开发者_如何学运维f, to the hash?

I have this code

foreach my $key (keys %ad_grp) {

    # Do something
}

which works.

How would the same look like, if I don't have %ad_grp, but a reference, $ad_grp_re开发者_如何学运维f, to the hash?


foreach my $key (keys %$ad_grp_ref) {
    ...
}

Perl::Critic and daxim recommend the style

foreach my $key (keys %{ $ad_grp_ref }) {
    ...
}

out of concerns for readability and maintenance (so that you don't need to think hard about what to change when you need to use %{ $ad_grp_obj[3]->get_ref() } instead of %{ $ad_grp_ref })


In Perl 5.14 (it works in now in Perl 5.13), we'll be able to just use keys on the hash reference

use v5.13.7;

foreach my $key (keys $ad_grp_ref) {
    ...
}


As others have stated, you have to dereference the reference. The keys function requires that its argument starts with a %:

My preference:

foreach my $key (keys %{$ad_grp_ref}) {

According to Conway:

foreach my $key (keys %{ $ad_grp_ref }) {

Guess who you should listen to...

You might want to read through the Perl Reference Documentation.

If you find yourself doing a lot of stuff with references to hashes and hashes of lists and lists of hashes, you might want to start thinking about using Object Oriented Perl. There's a lot of nice little tutorials in the Perl documentation.


With Perl 5.20 the new answer is:

foreach my $key (keys $ad_grp_ref->%*) {

(which has the advantage of transparently working with more complicated expressions:

foreach my $key (keys $ad_grp_obj[3]->get_ref()->%*) {

etc.)

See perlref for the full documentation.

Note: in Perl version 5.20 and 5.22, this syntax is considered experimental, so you need

use feature 'postderef';
no warnings 'experimental::postderef';

at the top of any file that uses it. Perl 5.24 and later don't require any pragmas for this feature.

0

精彩评论

暂无评论...
验证码 换一张
取 消