Chris R
Chris R

Reputation: 735

Regexp search and replace as variables in Perl

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+).

Upvotes: 2

Views: 768

Answers (3)

Ven'Tatsu
Ven'Tatsu

Reputation: 3625

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;

Upvotes: 0

bvr
bvr

Reputation: 9697

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 

Upvotes: 5

bw_üezi
bw_üezi

Reputation: 4564

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

Upvotes: 1

Related Questions