How to use foreach with a hash reference?

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

    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.

    0 讨论(0)
  • 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 })

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-15 17:51

    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) {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题