LoginSignup
9
8

More than 5 years have passed since last update.

Perlで2つの配列の要素から重複を排除する、重複した要素だけ抽出する

Posted at

2つの配列から要素の重複を排除してユニークな要素の配列を作成

make_array_unique.pl
# 例えばこんな配列の場合
my @array_a = qw(1 2 3 4 5 6 7 8 9 10);
my @array_b = qw(2 4 6 8 10);

my %count;
my @unique;
$count{$_}++ for (@array_a, @array_b); # @array_aと@array_bの要素がそれぞれいくつあるかを計算
@unique = grep { $count{$_} < 2 } keys %count; # 要素数が2より小さいもののみ抽出

↓みたいな感じで結果を表示させると

make_array_unique.pl
foreach (@unique) {
      print "$_\n";
};
----
hoge# perl make_array_unique .pl
3
7
9
1
5

となる。

重複した要素を抽出

上↑のコードから以下の部分を変更するだけ。

make_array_unique.pl
@unique = grep { $count{$_} >= 2 } keys %count; # 要素数が2より小さいもののみ抽出

結果を出力させると↓。

hoge# perl make_array_unique .pl
6
2
8
4
10

という感じで、foreach使ってガリガリやるより楽な感じがします。

9
8
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8