开发者

Regexp search and replace as variables in Perl

开发者 https://www.devze.com 2023-02-08 23:46 出处:网络
I can\'t find a solution to this and开发者_开发问答 its driving me crazy! my $foo = qr/(\\S+) (\\X+)/;

I can't find a solution to this and开发者_开发问答 its driving me crazy!

my $foo = qr/(\S+) (\X+)/;
my $bar = qr/$2/;

line =~ s/$foo/$bar/g 

My problem is that $bar uses a previously defined value of $2 rather than the (\X+).


Please note that second part of s is not regex, but rather string to replace regex found. You can achieve what you want with this (note ee double-eval option at the end):

my $foo = qr/(\S+) (\X+)/;
my $bar = '$2';             # no interpolation

$line =~ s/$foo/$bar/gee;   # first eval make $bar -> '$2', second replaces it 


I guess value of $bar should just be a string and not a regex. The qr// doesn't look right there.


Similar to bvr's suggestion you can use a sub ref for the replacement side of s///. This has the advantage of being precompiled (both the sub ref, and the substitution) as opposed to being recompiled for each match. In most cases this will be faster and more likely to catch any errors at compile time.

my $foo = qr/(\S+) (\X+)/;
my $bar = sub { $2 }; # or my $bar = \&some_replace_function;

$line =~ s/$foo/$bar->()/ge;
0

精彩评论

暂无评论...
验证码 换一张
取 消