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"}";
}
非常感谢。您可以通过使用循环搜索元素来减少代码
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}}}{…}
!!非常感谢。现在我将能够改进我的程序。