2014-08-27 76 views
0

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 

我想打一個如果 「如果任何這些2個變量的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語句)

回答

1

您可以使用哈希來快速檢查是有一個if語句兩個陣列中的常見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"; 
+0

這絕對有效!問題是,我對perl非常陌生,而且我很難理解它/使用它我喜歡它。基本上,如果我找到一個匹配,我想執行更多的代碼。如果我找不到匹配項,我想執行一組不同的代碼。 因此,我不想打印,我想要的東西。 如果符合:請執行此代碼 如果不符合:請執行所有其他代碼 – 2014-09-03 17:41:27

+1

明白了:) Perl很有趣! if($ matches){ \t \t print「這個域名指向這臺服務器!」,「\ n」; \t \t \t #Apache開始 \t}其他{ \t \t打印 「此域名不指向該服務器!」, 「\ n」; \t} – 2014-09-03 19:09:00

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; 
相關問題