2つの配列を比較して、違いや一緒の部分を洗い出すやり方[perl]

・下記そのコード
@union = @intersection = @difference = ();
%count = ();
foreach $element (@array1, @array2) { $count{$element}++ }
foreach $element (keys %count) {
push @union, $element;
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}
・使い方
@array1 = ('君','の','話','は','。');
@array2 = ('君','の','恋の','話');

@union = @intersection = @difference = ();
%count = ();
foreach $element (@array1, @array2) { $count{$element}++ }
foreach $element (keys %count) {
push @union, $element;
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}
#@union = (は,君,。,の,恋の,話,) →合わせてすべての値
#@intersection = (君,の,話) → 交差する部分
#@differense = (は,。,恋の,) → 違う部分

参考:http://coding.derkeiler.com/Archive/Perl/comp.lang.perl.misc/2009-11/msg00363.html

おすすめ

コメントを残す

メールアドレスが公開されることはありません。

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください