How to use foreach with a hash reference?

前端 未结 4 1789
孤城傲影
孤城傲影 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:44

    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.

提交回复
热议问题