Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何使用grep在PERL中检查数组中的元素?_Arrays_Perl - Fatal编程技术网

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

Arrays 如何使用grep在PERL中检查数组中的元素?,arrays,perl,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

我想检查数组中是否有元素

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"}";
}
  • 如何将哈希转换为数组
  • 我不确定grep语法“$\”是否正确
  • 我只是PERL的初学者


    非常感谢。

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

    for my $ip (@ips_to_find) {
       for my $key (keys(%hash)) {
          print("$ip in $key\n")
             if grep { $_ eq $ip } @{ $hash{$key} };
       }
    }
    
    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>
    

    if(grep{$table[0]eq${$hash{Value1}}}{…}
    !!非常感谢。现在我将能够改进我的程序。