値が配列であるハッシュがあります。これらの配列の共通要素を見つける必要があります。すべての配列に存在する要素。そこで、ハッシュの値を抽出して、各行がハッシュ内の配列に対応する多次元配列にしました。次に、このマトリックスの最初の行を別の配列 (@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 での作業がより簡単になる可能性があることを知りたいと思っています。私のコードが実行できる最高のものである場合は、それもお知らせください。任意のガイダンスをいただければ幸いです。ありがとう!