Arrays Perl:在数组中搜索项

Arrays Perl:在数组中搜索项,arrays,perl,variables,hash,perl-data-structures,Arrays,Perl,Variables,Hash,Perl Data Structures,给定一个数组@A,我们想检查元素$B是否在其中。一种说法是: Foreach $element (@A){ if($element eq $B){ print "$B is in array A"; } } 然而,当谈到Perl时,我总是在考虑最优雅的方式。这就是我的想法: 如果我们将a转换为变量字符串并使用 index(@A,$B)=>0 有可能吗?有很多方法可以确定元素是否存在于数组中: use 5.10.1; $B ~~ @A and say '

给定一个
数组@A
,我们想检查
元素$B
是否在其中。一种说法是:

Foreach $element (@A){
    if($element eq $B){
        print "$B is in array A";
    }
}
然而,当谈到Perl时,我总是在考虑最优雅的方式。这就是我的想法: 如果我们将a转换为变量字符串并使用

index(@A,$B)=>0
有可能吗?

有很多方法可以确定元素是否存在于数组中:

use 5.10.1;

$B ~~ @A and say '$B in @A';
  • 使用foreach

    foreach my $element (@a) {
        if($element eq $b) {
           # do something             
           last;
        }
    }
    
  • 使用Grep:

    my $found = grep { $_ eq $b } @a;
    
    use List::Util qw(first); 
    
    my $found = first { $_ eq $b } @a;
    
  • 使用模块

    my $found = grep { $_ eq $b } @a;
    
    use List::Util qw(first); 
    
    my $found = first { $_ eq $b } @a;
    
  • 使用由切片初始化的哈希值

    my %check;
    @check{@a} = ();
    
    my $found = exists $check{$b};
    
  • 使用由map初始化的哈希

    my %check = map { $_ => 1 } @a;
    
    my $found = $check{$b};
    

  • 相关:在这种情况下,我建议首先使用
    ,因为它不必遍历整个数组。当找到项时,它可以停止。任何元素也可以停止,因为它只需要一个元素为true。请注意,
    first
    也可以在找到项时返回假值,例如“0”,这会混淆此答案中给出的示例<代码>任何都具有所需的语义。您必须非常小心,因为这会将匹配分布到元素上。如果@A有一个包含$B的数组引用元素,即使$B不是@A的顶级元素,该元素仍将匹配。由于这一点和许多其他原因,智能匹配从根本上被破坏。List::Util::first()示例在搜索假值时(可能)会有细微的错误,因为
    $found
    也会计算假值。(
    die除非$found
    …oops!)在这里做了正确的事情。