in reply to can't get $& to remove value in a substitution

Strangely, the following seems to work for me:
$content = qq(<textarea class="FolderTxtArea" name="blah"><%=foo::doSo +mething%></textarea>); while ($content =~ m/(<textarea.*textarea>)/sg) { my $match = $&; my $varmatch; print "match: before ..... $match\n"; if( $match =~ m/(<%=.*?%>)/sg){ $varmatch = $1; print "varmatch: $varmatch\n"; pos $match ; #cut var tag $match=~ s/$varmatch//g; print "match: after .... $match\n"; $match=~ s/textarea/testinsert$varmatch/g; print "match: after testinsert .... $match\n"; } }
Gives output:
match: before ..... <textarea class="FolderTxtArea" name="blah"><%=foo +::doSomething%></textarea> varmatch: <%=foo::doSomething%> match: after .... <textarea class="FolderTxtArea" name="blah"></texta +rea> match: after testinsert .... <testinsert<%=foo::doSomething%> class=" +FolderTxtArea" name="blah"></testinsert<%=foo::doSomething%>>
Are you sure you are looking at the output from your latest run?

Replies are listed 'Best First'.
Re: Re: can't get $& to remove value in a substitution
by zusuki-san (Initiate) on Oct 24, 2002 at 14:17 UTC
    thanks for your input monks, it's much appreciated :)
    i've discovered the problem...
    the actual match i was trying to replace has parentheses within it, which is buggering up the process.

    if i try and replace:
     $content = qq(<textarea class="FolderTxtArea" name="blah"><%=foo::doSomething %></textarea>);

    it works.
    however, if i try:
     $content = qq(<textarea class="FolderTxtArea" name="blah"><%=foo::doSomething ()%></textarea>);# note the parentheses after doSomething

    it fails.

    now i have to figure out a good way to escape the parentheses inside a variable.
    i could just go in and temporarily replace them, which seems like a bit of a hack
    if anyone is aware of a more elegant way of doing this i'd love to hear it.
    once again, my thanks for your help

    p.s. one lesson here is to copy and paste code verbatim for others to try. my apologies
    only reason i didn't was for readability- the string i was trying to replace is awful long and ugly looking :)
      This is from the perlre manpage. I've not used it before so this is a first stab:
      \Q quote (disable) pattern metacharacters till \E
      my $pattern = "ABC()DEF"; my $string = "ABC()DEF"; if ($string =~ /\Q$pattern\E/) { print "match 1\n" } if ($string =~ /$pattern/) { print "match 2\n" }
      You can see that putting your variable between \Q and \E in the regex disables the ( and ) metacharacters in the pattern. (I think!).