对Perl来说还是非常新的,请原谅我,如果这看起来完全基本但我已经谷歌搜索了很长一段时间。我有2个变量;两行都有多个IP地址。
变量$ a
111.11.11.11
333.33.33.33
111.11.11.11
变量$ b
222.22.22.22
111.11.11.11
222.22.22.22
我想制作一个if语句"如果这两个变量中的任何一个ips匹配,那么继续"。例如:
print "What is the website that is offline or displaying an error?";
my $host = readline(*STDIN);
chomp ($host);
# perform the ping
if( $p->ping($host,$timeout) )
{
#Host replied! Time to check which IP it is resolving to.
my $hostips = Net::DNS::Nslookup->get_ips("$host");
$hostips =~ s/$host.//g;;
}
#We have a list of IPs, now we need to make sure that IP resolves to this server.
#This is where the 2nd if statement begins (making sure one of the ips in both arrays match).
else
{
print "".$host." is not pinging at this time. There is a problem with DNS\n";
}
$p->close();
我必须记住,这是if语句中的if语句(如果语句将继续使用更多语句)
答案 0 :(得分:1)
您可以使用哈希快速检查两个阵列中是否存在公共IP:
#!/usr/bin/perl
use warnings;
use strict;
my @array1 = qw( 111.11.11.11
333.33.33.33
111.11.11.11
);
my @array2 = qw( 222.22.22.22
111.11.11.12
222.22.22.22
);
my %match;
undef @match{@array1};
my $matches;
for my $ip (@array2) {
$matches = 1, last if exists $match{$ip};
}
print $matches ? 'Matches' : "Doesn't match", "\n";
答案 1 :(得分:0)
如果您的两个列表中都出现了IP地址,您可以使用类似的内容。
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use List::MoreUtils 'uniq';
my @array1 = qw( 111.11.11.11
333.33.33.33
111.11.11.11
);
my @array2 = qw( 222.22.22.22
111.11.11.11
222.22.22.22
);
# Remove duplicates from each array
@array1 = uniq @array1;
@array2 = uniq @array2;
my %element;
# Count occurances
$element{$_}++ for @array1, @array2;
# Keys with the value 2 appear in both array
say $_ for grep { $element{$_} == 2 } keys %element;