我有一个包含字符串file1
的第一个文件All cars are red.
我想用另一个单词列表从初始字符串list1
替换单词列表(cars red
) list2
包含boats blue
以获得此输出
All boats are blue.
这里的目标是使用更大的单词列表进行替换,并使用更大的字符串来替换多个单词。
我猜代码应该是这样的:
use strict;
use warnings;
open (my $list1, "<", "list1.txt") or die "cannot open list1\n";
open (my $list2, "<", "list2.txt") or die "cannot open list2\n";
open (my $file1, "<", "file1.txt") or die "cannot open file1\n";
my @replacer = <$list2>;
my @tobereplaced = <$list1>;
foreach my $word (@replacer) {
my $file1 =~ s/$tobereplaced/$word/gee; }
有人可以帮助我获得所需的输出吗?
答案 0 :(得分:2)
@tobereplaced = map split, @tobereplaced;
@replacer = map split, @replacer;
my %replacements;
@replacements{@tobereplaced} = @replacer;
my $pat = join '|', map quotemeta, @tobereplaced;
my $re = qr/$pat/;
while (<$file1>) {
s/\b($re)\b/$replacements{$1}/g;
print;
}
你没有指定输入文件的格式,所以我不得不做一些猜测。