Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.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 使用Perl查找数组中的值_Arrays_Perl - Fatal编程技术网

Arrays 使用Perl查找数组中的值

Arrays 使用Perl查找数组中的值,arrays,perl,Arrays,Perl,我有两个数组@input0和@input1。我想要一个for循环,它遍历@input1中的每个值,如果该值存在于@input0中,则该值将保存在新数组@input中 所有数组仅包含数字。每个数组元素最多有10个数字,请参见下文: @input0 = {10061 10552 10553 10554 10555 10556 10557 10558 10559 10560, 10561 10562 10563 10564 10565 10566 10567 10573 10574 10575, ..

我有两个数组@input0和@input1。我想要一个for循环,它遍历@input1中的每个值,如果该值存在于@input0中,则该值将保存在新数组@input中

所有数组仅包含数字。每个数组元素最多有10个数字,请参见下文:

@input0 = {10061 10552 10553 10554 10555 10556 10557 10558 10559 10560, 10561 10562 10563 10564 10565 10566 10567 10573 10574 10575, ...}

@input1 = {20004 20182 ...}

在Perl中实现这一点的最简洁和惯用的方法不是使用for循环,而是使用map和grep

如果您特别想要一个for循环,请解释为什么map/grep方法不起作用,除非它是一个家庭作业,在这种情况下,问题应该标记为一个

短、甜、慢:

my @input = grep $_ ~~ @input0, @input1;
使用for循环可以更详细、更快:

my %input0 = map {$_, 1} @input0;
my @input;

for (@input1) {
    push @input, $_ if $input0{$_};
}

您还可以使用hashslice+grep:

my %tmp ;
@tmp{@input0} = undef ; # Fill all elements of @input0 in hash with value undef
my @input = grep { exists $tmp{$_} } @input1 ; # grep for existing hash keys

dgw的回答几乎是正确的,但包含了一些不是最佳实践的东西。我认为这样更好:

my %input0_map;
@input0_map{ @input0 } = ();
my @input = grep { exists $input0_map{$_} } @input1;
除非变量的作用域很小,否则不应将其命名为“tmp”。由于此代码段没有包装在大括号块中,因此我们不知道作用域有多大


您不应该使用单个“undef”分配到哈希片中,因为这意味着第一个元素被分配了该文本undef,而其他元素被分配了隐式undef。这行得通,但风格不好。要么给它们全部赋值,要么像从空列表赋值一样隐式赋值。

Smart Match只在Perl 5.10及更高版本中起作用,在早期版本中不起作用。这对于大型数组也比较慢,因为它在*M扫描时起作用,而不是在+M as map+grep中起作用。这是正确的,但在惯用的解决方案方面,你比我强。如果有什么问题的话,这个解决方案可以让你一眼就知道它正在创建两个数组的交集,但这似乎不起作用。我猜这是因为每个数组元素有多个数字,最多10个,用空格分隔。对不起,我应该提一下。那么,我是否最好先将数组拆分为每个元素的单个数字?Thanks@charleshendry-如果您有一个空格分隔的字符串,则它不称为数组。你需要给出更准确的描述和说明examples@input0={10061 10552…,10561…}不是有效的perl语法,并且会给出错误,例如在运算符期望的位置找到的数字。您需要引用字符串10061 10552。。。。另外,花括号{}创建一个散列引用。在指定给数组时,需要常规参数。
my %input0_map;
@input0_map{ @input0 } = ();
my @input = grep { exists $input0_map{$_} } @input1;