如何在perl中执行“值的内部联接”

时间:2019-10-16 08:03:04

标签: perl

我在perl中有两个数组,需要根据它们的第3列的第一个值合并成一个数组,如下所述;

Array1:

0 1 3 some text

0 1 6 more text

1 2 0 and more

Array2:

0 1 3 where missing on page2

1 2 0 to do with it

0 1 6 to read on tuesday

我想实现:

0 1 3 some text where missing on page2

0 1 6 more text to read on tuesday

1 2 0 and more to do with it

能在需要时提供帮助并提供一些解释吗?

1 个答案:

答案 0 :(得分:1)

欢迎使用堆栈溢出。您应该发布到目前为止已经尝试过的内容:),这样人们就会理解并帮助/解决您的问题。

如果我了解您的问题,让我们考虑一下您有如下所示的array数组。我们必须比较两个数组直到指定的索引值。因此,我使用了名为$matchedColums的变量名。然后我们必须进行嵌套循环以比较两个数组值。

所以我要做的是,我从给定的索引中获取了值,并与这两个值进行比较,然后推入另一个数组。然后,您可以获得新的数组。

use warnings;
use strict;
use Data::Dumper;

my $array =  [["0","1","3","some text"], ["0","1","6","more text"], ["1","2","0","and more"]];

my $array1 =  [["0","1","3","where missing on page2"], ["0","1","6","to do with it"], ["1","2","0","to read on tuesday"]];

my $matchedColums = 3;
my $mc = $matchedColums-1;


my @finalArray ;

for my $a1 (@{$array}){ #Iterating loop for array elements.

    my $matchA1 = join ( "" , @{$a1}[0..$mc] );    # joining the elements from the given index
    my @a2String;

    for my $a2 (@{$array1}){
        my $matchA2 = join ( "" , @{$a2}[0..$mc] );    
        if ($matchA1 == $matchA2) { 
            @a2String = @{$a2}[$mc+1..$#$a2];
            last;
        }
    }

    my @fn = (@{$a1}, @a2String);
    push @finalArray, \@fn; #pushing it as an array reference.

}

print Dumper \@finalArray;