好吧,主要是它不起作用,因为tr///d
与您的请求无关(tr/abc/12/d
用 1 替换 a,用 2 替换 b,并删除 c)。此外,默认情况下,数组不会以对您的任务有用的方式插入到正则表达式中。此外,如果没有哈希查找或子例程调用或其他逻辑之类的东西,您就无法在操作的右侧做出决定s///
。
要回答标题中的问题,您可以同时执行多个替换 - 呃,方便的连续 - 以这种方式:
#! /usr/bin/env perl
use common::sense;
my $sentence = "hello world what a lovely day";
for ($sentence) {
s/what/it's/;
s/lovely/bad/
}
say $sentence;
做一些更像你在这里尝试的事情:
#! /usr/bin/env perl
use common::sense;
my $sentence = "hello world what a lovely day";
my %replace = (
what => "it's",
lovely => 'bad'
);
$sentence =~ s/(@{[join '|', map { quotemeta($_) } keys %replace]})/$replace{$1}/g;
say $sentence;
如果您要进行大量此类替换,请先“编译”正则表达式:
my $matchkey = qr/@{[join '|', map { quotemeta($_) } keys %replace]}/;
...
$sentence =~ s/($matchkey)/$replace{$1}/g;
编辑:
并扩展我关于数组插值的评论,您可以更改$"
:
local $" = '|';
$sentence =~ s/(@{[keys %replace]})/$replace{$1}/g;
# --> $sentence =~ s/(what|lovely)/$replace{$1}/g;
确实,这并不能改善这里的情况,尽管如果您已经在数组中拥有了键,则可能会这样:
local $" = '|';
$sentence =~ s/(@keys)/$replace{$1}/g;