Michael
Michael

Reputation: 309

using variable as regex substitution parameter

I've been doing some searching and haven't found an answer. Why isn't this working?

    $self->{W_CONTENT} =~ /$regex/;
    print $1; #is there a value? YES
    $store{URL} =~ s/$param/$1/;

Yes $1 has a value. $param is replaced however it is replaced with nothing. I'm positive $1 has a value. If I replace with text instead of "$1" it works fine. Please help!

Upvotes: 1

Views: 732

Answers (2)

Sodved
Sodved

Reputation: 8607

For $1 to have a value you need to ensure that $param has parentheses () in it. i.e. The following has a problem similar to what you are explaining.

my $fred = "Fred";
$fred =~ s/red/$1/;
# $fred will now be "F"

But this works

my $fred = "Fred";
$fred =~ s/r(ed)/$1/;
# $fred will now be "Fed"

Now if you want to use the $1 from your first regex in the second one you need to copy it. Every regex evaluation resets $1 ... $&. So you want something like:

$self->{W_CONTENT} =~ /$regex/;
print $1; #is there a value? YES
my $old1 = $1;
$store{URL} =~ s/$param/$old1/;

Upvotes: 6

Christopher
Christopher

Reputation: 774

Backreferences such as $1 shouldn't be used inside the expression; you'd use a different notation - for an overview, check out Perl Regular Expressions Quickstart.

Consider getting the value of $1 and storing it in another variable, then using that in the regex.

Upvotes: 1

Related Questions