如何在保留原始字符串的同时对字符串执行Perl替换?
时间:2020-03-05 18:42:07 来源:igfitidea点击:
在Perl中,有什么好方法可以使用正则表达式对字符串进行替换并将值存储在不同的变量中,而无需更改原始值?
我通常只是将字符串复制到一个新变量中,然后将其绑定到对新字符串进行替换的s /// regex中,但是我想知道是否有更好的方法来做到这一点?
$newstring = $oldstring; $newstring =~ s/foo/bar/g;
解决方案
回答
这是我惯常使用的成语,无需更改原始字符串即可获取字符串的修改后的副本:
(my $newstring = $oldstring) =~ s/foo/bar/g;
在perl 5.14.0或者更高版本中,可以使用新的/ r
无损替换修饰符:
my $newstring = $oldstring =~ s/foo/bar/gr;
注意:以上解决方案也可以在不使用g的情况下工作。它们还可以与任何其他修饰符一起使用。
回答
该声明:
(my $newstring = $oldstring) =~ s/foo/bar/g;
等效于:
my $newstring = $oldstring; $newstring =~ s/foo/bar/g;
另外,从Perl 5.13.2开始,我们可以使用/ r
进行非破坏性替换:
use 5.013; #... my $newstring = $oldstring =~ s/foo/bar/gr;
回答
如果用use strict;
来编写Perl,那么即使声明了,单行语法也是无效的。
和:
my ($newstring = $oldstring) =~ s/foo/bar/;
你得到:
Can't declare scalar assignment in "my" at script.pl line 7, near ") =~" Execution of script.pl aborted due to compilation errors.
取而代之的是,我们一直在使用的语法(长了一行)是使用" use strict;"进行语法处理的正确方法。对我来说,使用use strict;
现在只是一种习惯。我会自动执行。大家应该。
#!/usr/bin/env perl -wT use strict; my $oldstring = "foo one foo two foo three"; my $newstring = $oldstring; $newstring =~ s/foo/bar/g; print "$oldstring","\n"; print "$newstring","\n";
回答
在"使用严格"下,说:
(my $new = $original) =~ s/foo/bar/;
反而。
回答
单行代码解决方案比起好的代码更有用。好的Perl编码人员会知道并理解它,但是它比起初使用的两行复制和修改对联的透明度和可读性要差得多。
换句话说,执行此操作的一种好方法是我们已经执行的操作。以可读性为代价的不必要的简洁并不是胜利。