如何在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};
}
对于FTP,例如我想将FTP分配给标量,然后将每个密钥从FTP(端口,pr,waitfor)分配给标量,以及在服务之间循环的foreach循环(ftp,ssh,dns等)。 ..)
感谢您的帮助。
答案 0 :(得分:3)
my $waitfor = $services->{$service}->{waitfor};
应该是
my $waitfor = $services->{$key}->{waitfor};
或者您可以使用以下内容:
for my $id (keys %$services) {
my $service = $services->{$id};
my $port = $service->{port};
my $waitfor = $service->{waitfor};
...
}
甚至
for my $service (values %$services) {
my $port = $service->{port};
my $waitfor = $service->{waitfor};
...
}