Reputation: 3175
How would I go about accessing the elements of this hash_ref within a foreach loop?
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...)
Thanks for the help in advance.
Upvotes: 0
Views: 102
Reputation: 418
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";
}
}
Upvotes: 1
Reputation: 386696
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};
...
}
Upvotes: 3