How to use foreach with a hash reference?

前端 未结 4 1796
孤城傲影
孤城傲影 2020-12-15 17:29

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

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 17:37

    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 })

提交回复
热议问题