【问题标题】:If any lines in 2 variable arrays match如果 2 个变量数组中的任何行匹配
【发布时间】:2014-10-21 06:52:54
【问题描述】:

对于 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 匹配,则继续”的 if 语句。例如:

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 语句(它将继续到更多的 if 语句中)

【问题讨论】:

    标签: arrays perl variables match


    【解决方案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";
    

    【讨论】:

    • 这绝对有效!问题是,我对 perl 很陌生,我在理解它/以我喜欢的方式使用它时遇到了一些麻烦。基本上,如果我找到匹配项,我想执行更多代码。如果我找不到匹配项,我想执行一组不同的代码。所以不是打印,我想要类似的东西。如果匹配:执行所有这些代码如果不匹配:执行所有其他代码
    • 知道了 :) Perl 很有趣! if ($matches){ print "这个域确实指向这个服务器!", "\n"; #Apache 开始 }else{ 打印 "此域不指向此服务器!", "\n"; }
    【解决方案2】:

    如果一个 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多