如何使用grep检查PERL中数组中的元素?

时间:2015-08-26 13:45:22

标签: arrays perl

我想检查一个元素是否在数组中?

my %hash = (
 Value1 => ['10.0.0.1', '10.0.0.2'],
); #/!\NOT ARRAY

my @table = ( '10.0.0.6', '10.0.0.1');

伪代码

my $i = 0;
if( grep { $table[0] eq $_ } eq $hash{"Value1[]"} ) {
 print "Find!!!";
 $i++; #true
}
if( grep { $table[1] eq $_ } eq $hash{"Value1[]"} ) {
 print "Find!!!";
 $i++; #true
}

if ( $i = 2) {
 print "It is perfect. 0% difference between table and hash{"Value1"}";
}
if ( $i = 1) {
 print "It is middle. 50% difference between table and hash{"Value1"}";
}
if ( $i = 0) {
 print "It is bad. 100% difference between table and hash{"Value1"}";
}
  1. 如何将哈希转换为数组? Use grep in PERL
  2. 我不确定grep语法“$ _”??
  3. 我只是PERL的初学者。

    非常感谢。

2 个答案:

答案 0 :(得分:0)

for my $ip (@ips_to_find) {
   for my $key (keys(%hash)) {
      print("$ip in $key\n")
         if grep { $_ eq $ip } @{ $hash{$key} };
   }
}

答案 1 :(得分:0)

您可以使用循环搜索元素来减少代码。

my %hash = ('Value1' => ['10.0.0.1', '10.0.0.2'] ); 
    my @table = ( '10.0.0.6', '10.0.0.1');

    my $i = 0;
    for my $val (@table) {
        if (grep $_ eq $val, @{ $hash{'Value1'} })
       {
            print "Find!!!\n";
        $i++;
        }
    }

    if ( $i == 2) {
     print "It is perfect. 0% difference between table and hash{'Value1'}";
    }
    elsif ( $i == 1) {
     print "It is middle. 50% difference between table and hash{'Value1'}";
    }
    elsif ( $i == 0) {
     print "It is bad. 100% difference between table and hash{'Value1'}";
    }

输出

G:\Study\Perl Arsenal>perl temp.pl
Find!!!
It is middle. 50% difference between table and hash{'Value1'}
G:\Study\Perl Arsenal>