1

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!

2 Answers 2

6

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/;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you!! This worked great. I was playing around with the brackets but I did not think that $1 was reset. Tricky!
You might consider s/\Q$param\E/$old1/ if there is any chance that $param will contain meta characters.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.