Wassercrats has asked for the wisdom of the Perl Monks concerning the following question:

Why does
@links1="<a href=\"www\.testurl\.com\">"; @links1=~s/.*/href\s*\=\s*\".*?\"/is;
make @links1 contain:
hrefs*=s*".*?"
instead of:
href="www.testurl.com"
???
I don't want the s* and .*? to be literal.

Replies are listed 'Best First'.
Re: Substitution Problem
by dws (Chancellor) on Sep 10, 2002 at 04:34 UTC
    Instead of
    @links1="<a href=\"www\.testurl\.com\">"; @links1=~s/.*/href\s*\=\s*\".*?\"/is;
    try
    $links1 = '<a href="www.testurl.com">'; $links1 =~ s/<a\s+(href=".*?")\s*>/$1/is;
    You're escaping more than you need to in the regex, and you're not capturing the the left-hand side the subset of the string that you want to make the replacement with on the right-hand side.

      I figured Perl's greedyness would allow .* to capture the entire string. Your suggestion worked (I changed a few things to make it work like I really need it to work):
      $links1 =~ s/.*<\s*a\s*(href\s*=\s*".*?").*>.*/$1/is;
      but out of curiosity, isn't there a simple regex to indicate the entire string that I can put on the left so I can specify what I want replaced on the right without memory brackets?

        Don't confuse matching with capturing:

        s/$a/$b/ # $a matches and is replaced by $b s/($a)/$1$b/ # $a matches and is captured in $1 # $b is appended
        Note also, that you can't use character classes like "." or "\s" within the right side of the substitute operator.

        ~Django
        "Why don't we ever challenge the spherical earth theory?"

        ...meant that I'd like to put the replacement string on the right. I want to replace the entire string.