【发布时间】:2019-02-28 20:39:59
【问题描述】:
#!usr/bin/perl -W
use strict;
my @a = (3,5,8,6,7,9);
my @b = (3,7,8);
my @index;
my $match;
foreach my $i (0 .. $#a) {
$match = 0;
foreach my $j (0 .. $#b) {
if ($a[$i] == $b[$i]) {
$match = 1;
push (@index, $j);
last;
}
}
if ($match == 1) {
print "the values which got matched are $a[$i] at a and index is $i\n";
}
}
print "the index of b matched is @index";
您好,我想获取数组元素匹配的索引和值。
my @a=(3,5,8,6,7,9);
my @b=(5,9,3);
我想比较@a 和@b 并从a 中获取匹配值的索引。 (比较值,ia) 输出是这样的([5,9,3],[1,5,0])。 b 值 5 与索引 1 中的 a 匹配。
有人可以帮我解决这个问题吗?我试图首先获取匹配的数组元素并在找到匹配时推送索引。但是没有得到预期的结果。
【问题讨论】:
-
SO 不是免费的代码编写服务。您能否编辑问题以显示您已经尝试过的内容。
-
如果我添加 != 并在 match =0 时提取元素,我得到 b 中不存在的元素的输出。但我想要匹配的元素及其索引。
-
您的代码甚至无法编译
-
我改进了代码的缩进。不客气,但请以后自己做。正确缩进的代码更易于阅读和理解。
-
if ($match = 1)- 你是这个意思吗?我怀疑你实际上想要if ($match == 1)甚至只是if ($match)。
标签: perl comparison matching