As for writing to the same file, please note Vinko answer. As for replacing strings, please check this snippet:
my @arr1 = ("AA", "BB", "CC", "DD", "EE");
my %replacements = map { ($arr1[$_] => $_ + 1) } (0..$#arr1);
my $regexp = join( '|', sort { length($b) <=> length($a) } @arr1);
open F2, $file;
while (<F2>) {
my $str = $_;
$str =~ s/($regexp)/$replacements{$1}/ge;
print $str;
}
close(F2);
Important parts:
my %replacements = map { ($arr1[$_] => $_ + 1) } (0..$#arr1);
It builds hash with keys from @arr1, and values are the index of given value in @arr1 incremented by 1.
For example, for @arr1 = ("a", "b", "d", "c"); %replacements will be: ("a" => 1, "b", => 2, "c" => 4, "d" => 3);
my $regexp = join( '|', sort { length($b) <=> length($a) } @arr1);
This builds base regexp for finding all words from @arr1. The sort part orders words by their length descending. So, for @arr1 = ("a", "ba", "bac") $regexp will be 'bac|ba|a'.
This ordering is important as otherwise there would be problems if any of the words would be prefix of any other word (as with "ba" and "bac" in my example).
As a last word, usage of filehandles as FH is rather discouraged, as these are globals, and generate "interesting" problems in more complex programs. Instead use open like this:
open my $fh, 'filename';
or better yet:
open my $fh, '<', 'filename';