wjb@moscom.UUCP (Bill de Beaubien) (06/12/91)
While working on a Perl script a little while back, I found myself trying to substitute occurances of the contents of a variable with nothing. This is a straight-forward thing, except that the string I was trying to match on contained parentheses, which Perl took as RE parens rather the text parens. Easy enough to solve, but the solution I came up with just didn't appeal to me esthetically; it seems kind of bulky, and I have to wonder if there isn't a better way. So, tell me... is there a better way? This is the code I came up with; The list I'm trying to remove from is in $nodes{$elt}, and the pattern I'm trying to remove is in $elt. ... $nodes{$elt} .= join(" ",@list); $ptrn=$elt; $ptrn=~s/([\(\)])/\\$1/g; ($nodes{$elt}) =~ s/(.*)$ptrn(.*)/$1$2/ ... -- "Bless me, Father; I ate a lizard." "Was it an abstinence day, and was it artificially prepared?" ------------------------------------------------------------- Bill de Beaubien / wjb@moscom.com
tchrist@convex.COM (Tom Christiansen) (06/16/91)
From the keyboard of wjb@moscom.UUCP (Bill de Beaubien): :While working on a Perl script a little while back, I found myself trying :to substitute occurances of the contents of a variable with nothing. This :is a straight-forward thing, except that the string I was trying to match :on contained parentheses, which Perl took as RE parens rather the text :parens. Easy enough to solve, but the solution I came up with just didn't :appeal to me esthetically; it seems kind of bulky, and I have to wonder :if there isn't a better way. So, tell me... is there a better way? : :This is the code I came up with; The list I'm trying to remove from is :in $nodes{$elt}, and the pattern I'm trying to remove is in $elt. : :... : $nodes{$elt} .= join(" ",@list); : $ptrn=$elt; : $ptrn=~s/([\(\)])/\\$1/g; : ($nodes{$elt}) =~ s/(.*)$ptrn(.*)/$1$2/ From the FAQ: 18) How can I quote a variable to use in a regexp? From the manual: $pattern =~ s/(\W)/\\$1/g; Now you can freely use /$pattern/ without fear of any unexpected meta-characters in it throwing off the search. If you don't know whether a pattern is valid or not, enclose it in an eval to avoid a fatal run-time error. I think I might have written it this way: # (apparently in some kind of loop?) $nodes{$elt} .= " @list"; # then once and once only: ($ptrn = $elt) =~ s/(\W)/\\$1/g; $nodes{$elt} =~ s/$ptrn//g; --tom