How to use foreach with a hash reference?

2020-02-09 06:12发布

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_ref, to the hash?

标签: perl hash
4条回答
2楼-- · 2020-02-09 06:39

So, 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.

查看更多
\"骚年 ilove
3楼-- · 2020-02-09 06:56
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 })

查看更多
beautiful°
4楼-- · 2020-02-09 07:00

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.

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-02-09 07:01

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) {
    ...
}
查看更多
登录 后发表回答