in reply to replacing while keeping the position of the element in the file

It's not clear to me how, if you want to maintain the word lists strictly in parallel, your desired output isn't just @words1.

I think you might want something like this:

my %xlate; # open DOC1 here while (<DOC1>) { chomp; my($word_part) = split /_/; $xlate{$word_part} = $_; } # open DOC2 here while (<DOC2>) { s/(\S+)/$xlate{$1}/ge; print; }
Though that won't strip any newlines. Doing so isn't difficult.

We're not really tightening our belts, it just feels that way because we're getting fatter.