[Perl] => [配列]


この日記のはてなブックマーク数 このエントリーを含むはてなブックマーク
二つの配列の差分を調べるには以下のようにします。

[コード]
#!/usr/bin/perl

@one = qw(a a a a b c d e f g);
@two = qw(b c e h i i i i j);
my %tracker = ();
$tracker{$_} .= 1 for @one;
$tracker{$_} .= 2 for @two;

for (sort keys %tracker) {
  if ($tracker{$_} !~ /1/) {
    print "$_ has been added\n";
  }

  elsif ($tracker{$_} !~ /2/) {
    print "$_ has been deleted\n";
  }

  else {
    print "$_ is in both old and new\n";
  }
}


[実行例]
a has been deleted
b is in both old and new
c is in both old and new
d has been deleted
e is in both old and new
f has been deleted
g has been deleted
h has been added
i has been added
j has been added


モジュールではText::Diffというのが簡単。
use Text::Diff;

my $diff = diff \@one, \@two;


[参考文書] So what's the difference? (dec 00)

関連記事
無名配列 => 無名ハッシュのソート
配列をランダムに並び変え
配列の区切り文字
配列の差分
配列のソート
配列からユニークな要素の取り出し
map
grep - 文字列検索
unshift - 配列の最初に要素を追加するには
shift - 配列の最初の要素を取り除く
pop - 配列の最後の要素を取り除く
push - 配列の最後に要素を追加するには
reverse - 配列の順序を逆順にする
配列の個数を参照するには
広告