Perl 同时替换多个字符串 [英] Perl replace multiple strings simultaneously

查看:34
本文介绍了Perl 同时替换多个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法替换一个字符串中的多个字符串?例如,我有字符串 hello world 多么美好的一天,我想用其他东西替换 whatlovely ..

Is there any way to replace multiple strings in a string? For example, I have the string hello world what a lovely day and I want to replace what and lovely with something else..

$sentence = "hello world what a lovely day";
@list = ("what", "lovely"); # strings to replace
@replist = ("its", "bad"); # strings to replace with
($val = $sentence) =~ "tr/@list/@replist/d";
print "$val
"; # should print "hello world its a bad day"..

知道为什么它不起作用吗?

Any ideas why it's not working?

谢谢.

推荐答案

首先,tr 不能那样工作;详情请参阅perldoc perlop,但tr 是音译的,与替换有很大不同.

First of all, tr doesn't work that way; consult perldoc perlop for details, but tr does transliteration, and is very different from substitution.

为此,更正确的替换方法是

For this purpose, a more correct way to replace would be

# $val
$val =~ s/what/its/g;
$val =~ s/lovely/bad/g;

请注意,同时"更改相当困难,但我们可以做到,例如

Note that "simultaneous" change is rather more difficult, but we could do it, for example,

%replacements = ("what" => "its", "lovely" => "bad");
($val = $sentence) =~ s/(@{[join "|", keys %replacements]})/$replacements{$1}/g;

(当然,用元字符替换字符串可能需要转义.)

(Escaping may be necessary to replace strings with metacharacters, of course.)

这仍然只是一个非常松散的术语的同时,但在大多数情况下,它确实表现得好像替换是一次性完成的.

This is still only simultaneous in a very loose sense of the term, but it does, for most purposes, act as if the substitutions are done in one pass.

另外,将 "what" 替换为 "it's" 而不是 "its" 更正确.

Also, it is more correct to replace "what" with "it's", rather than "its".

这篇关于Perl 同时替换多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆