在Perl中,使用正则表达式对字符串执行替换并将值存储在不同的变量中而不改变原始值的好方法是什么?

我通常只是复制字符串到一个新变量,然后将其绑定到s///正则表达式,它对新字符串进行替换,但我想知道是否有更好的方法来做到这一点?

$newstring = $oldstring;
$newstring =~ s/foo/bar/g;

当前回答

如果使用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.

相反,您一直在使用的语法,虽然多了一行,但使用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";

其他回答

如果使用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.

相反,您一直在使用的语法,虽然多了一行,但使用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 $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;

这是我一直用来在不改变原始字符串的情况下获得修改后的字符串副本的习惯用法:

(my $newstring = $oldstring) =~ s/foo/bar/g;

在perl 5.14.0或更高版本中,你可以使用新的/r非破坏性替换修饰符:

my $newstring = $oldstring =~ s/foo/bar/gr; 

注意: 上述解在没有g的情况下也适用。它们也适用于任何其他修饰符。

参见: perldoc: Perl正则表达式快速入门

5.14之前的另一个解决方案:http://www.perlmonks.org/?node_id=346719(参见japhy的帖子)

由于他的方法使用map,它也适用于数组,但需要级联map来产生一个临时数组(否则原始数组将被修改):

my @orig = ('this', 'this sucks', 'what is this?');
my @list = map { s/this/that/; $_ } map { $_ } @orig;
# @orig unmodified

在使用严格的情况下,说:

(my $new = $original) =~ s/foo/bar/;

代替。