简体   繁体   English

Perl:访问哈希引用中的哈希元素

[英]Perl: Access hash elements within a hash ref

How would I go about accessing the elements of this hash_ref within a foreach loop? 我将如何在foreach循环中访问此hash_ref的元素?

use strict;
use warnings;

my $services = {
    ftp    => { port => 21,   pr => "",                      waitfor => '/220/'      },
    ssh    => { port => 22,   pr => "",                      waitfor => '/SSH/'      },
    domain => { port => 42,   pr => "",                      waitfor => ''           },
    http   => { port => 80,   pr => "HEAD / HTTP/1.0\n\n",   waitfor => '/200/'      },
    https  => { port => 443,  pr => "HEAD / HTTP/1.0\n\n",   waitfor => '/200/'      },
    pop3    => { port => 110, pr => "",                      waitfor => '/\+OK/'     },
    imap   => { port => 143,  pr => "",                      waitfor => '/OK/'       },
    smtp   => { port => 25,   pr => "",                      waitfor => '/SMTP/'     }
};


foreach my $key (keys %{ $services }) {
    my $port    = $service{port};
    my $waitfor = $services->{$service}->{waitfor};
}

For FTP for instance I want to assign FTP to a scalar and then each key from FTP (port, pr, waitfor) to scalars as well within the foreach loop that cycles between the services (ftp,ssh,dns,etc...) 例如,对于FTP,我想将FTP分配给一个标量,然后将FTP中的每个键(端口,pr,waitfor)分配给标量,以及在服务之间循环的foreach循环(ftp,ssh,dns等)中。

Thanks for the help in advance. 我在这里先向您的帮助表示感谢。

my $waitfor = $services->{$service}->{waitfor};

should be 应该

my $waitfor = $services->{$key}->{waitfor};

Or you can use something like: 或者,您可以使用类似:

for my $id (keys %$services) {
   my $service = $services->{$id};

   my $port    = $service->{port};
   my $waitfor = $service->{waitfor};
   ...
}

Or even 甚至

for my $service (values %$services) {
   my $port    = $service->{port};
   my $waitfor = $service->{waitfor};
   ...
}

you could do this easily.. 您可以轻松做到这一点。

foreach my $service (keys %$services)   {
print "serivce = $service \n";
foreach my $types (keys %$services->{$service}) {
    print "$services->{$service}->{$types} \n";
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM