我有一个哈希值是数组。我需要找到这些数组的共同元素,即。存在于所有数组中的元素。所以我将散列的值提取到一个多维数组中,其每一行对应于散列中的一个数组。然后我将该矩阵的第一行放入另一个数组 (@arr1) 并遍历它以查找 arr1 中是否有任何元素也在矩阵的其余行中。如果找到这样的元素,则将其推送到包含所有元素的最终列表的另一个数组中。代码如下(希望够清楚):
sub construct_arr(my %records) {
    my $len = keys %records;
    my @matrix;
    my $i = 0;
    # Extract the values of the hash into a matrix
    foreach my $key (keys %records) {
        $matrix[$i] = $records{$key};
        $i++;   
    }
    my @arr1 = $matrix[0];
    my @final;
    # Iterate through each element of arr1
    for my $j (0..$#{$arr1[0]}) {
        my $count = 1;
        # Iterate through each row of the matrix, starting from the second
        for ( my $i = 1; $i < $len ; $i++ ) {
            my $flag = 0;
            # Iterate through each element of the row
            for my $k (0..$#{$matrix[$i]}) {
                if ($arr1[0][$j] eq $matrix[$i][$k]) {
                    $flag = 1;
                    $count++;
                }
            }
            # On finding the first instance of the element in a row, go to the next row
            if (!$flag == 1) {
                last;
            }       
        }
        # If element is in all the rows, push it on to the final array
        if ($count == $len) {
            push(@final, $arr1[0][$j]);
        }
    }
    return @final;
}
我知道上述方法有效,但我想知道是否有任何其他(perlish)方法可以做到这一点。我开始学习 perl,我很想知道与其他语言相比,可以让我在 perl 中的工作更轻松的事情。如果我的代码是可以做到的最好的,也请告诉我。任何指导将不胜感激。谢谢!