Perl 从两个不同长度数组的比较中获取索引

Perl 从两个不同长度数组的比较中获取索引,perl,comparison,matching,Perl,Comparison,Matching,嗨,我想得到索引和数组元素匹配的值 #!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;

嗨,我想得到索引和数组元素匹配的值

#!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";
我想比较@a和@b,从a中得到匹配值的索引。 (比较值,ia) 输出如下([5,9,3],[1,5,0])。b值5在索引1中的a处匹配

有人能帮我吗。我试图首先获得匹配的数组元素,并在找到匹配项时推送索引。但是我没有得到预期的结果。

为什么您的代码不起作用 您的代码中有一个相当简单的输入错误

my @a=(3,5,8,6,7,9); 
my @b=(5,9,3);
您每次都使用
@a
中当前元素的
$i
索引访问
@b
中的相同值,然后按下从未用于比较的
$j
。您需要将
$a[$i]
$b[$j]
进行比较。这一个字母的变化将使该计划的工作

#                 V
if ($a[$i] == $b[$i]) {
    $match = 1;

    #              V
    push (@index, $j);
    last;
}
更好的方法 您的实现效率很低。您要做的是从
@b
中查找
@a
的内容。一个简单的方法是构建一个查找哈希(或者一个索引,比如电话簿侧面的字母)

代码迭代
@a
的值。它使用Perl5.12中添加的1。然后,它将它们按值放入散列中,这样您就可以在知道某个值时查找索引

然后,我们迭代
@b
中的值,并检查当前值的哈希中是否有
@a
的索引

输出如下所示

use strict;
use warnings;
use 5.012; # for say and each on array

my @a = ( 3, 5, 8, 6, 7, 9 );
my @b = ( 5, 9, 3 );
my @index;
my $match;

my %index_of_a;
while ( my ( $index, $value ) = each @a ) {
  $index_of_a{$value} = $index;    # will overwrite
}

foreach my $value (@b) {
  if ( exists $index_of_a{$value} ) {
    say "The index of '$value' in \@a is '$index_of_a{$value}'";
  }
}
如果
@a
中存在一个值不止一次,将使用最后一次出现的值。“我的代码”不跟踪
@b
的哪个索引在匹配时匹配。我将把这个留给你



1) 虽然我通常不喜欢使用
each
,但对于既需要值又需要索引的数组,我发现它比用于
循环的C样式
可读性好得多。

因此,这不是免费的代码编写服务。请编辑问题以显示您已尝试的内容。如果我添加!=并在match=0时提取元素,获得b中不存在的元素的输出。但是我想要匹配的元素和它们的索引。你的代码甚至没有编译。我已经改进了代码的缩进。不客气,但请以后自己动手。正确缩进的代码更容易阅读和理解。
如果($match=1)
-你的意思是?我怀疑你真的想要
if($match==1)
或者只是
if($match)
。嗨,谢谢你的回答。我还有一个问题@a=(3,5,8,6,7,9,9,8);那么,当它匹配时,我可以得到多个索引值吗?i、 例如,@a中'9'的索引是5,6?@Komala您必须使用数组引用作为查找哈希的值,并将索引推送到其中。如果你不知道这意味着什么,我建议你看一看。换句话说,用a{$value}=$index替换
$index\u与{$value},$index的
推送{$index},$index
use strict;
use warnings;
use 5.012; # for say and each on array

my @a = ( 3, 5, 8, 6, 7, 9 );
my @b = ( 5, 9, 3 );
my @index;
my $match;

my %index_of_a;
while ( my ( $index, $value ) = each @a ) {
  $index_of_a{$value} = $index;    # will overwrite
}

foreach my $value (@b) {
  if ( exists $index_of_a{$value} ) {
    say "The index of '$value' in \@a is '$index_of_a{$value}'";
  }
}
The index of '5' in @a is '1'
The index of '9' in @a is '5'
The index of '3' in @a is '0'