Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I efficiently handle multiple Perl search/replace operations on the same string?
    text
    copied!<p>So my Perl script basically takes a string and then tries to clean it up by doing multiple search and replaces on it, like so:</p> <pre><code>$text =~ s/&lt;[^&gt;]+&gt;/ /g; $text =~ s/\s+/ /g; $text =~ s/[\(\{\[]\d+[\(\{\[]/ /g; $text =~ s/\s+[&lt;&gt;]+\s+/\. /g; $text =~ s/\s+/ /g; $text =~ s/\.*\s*[\*|\#]+\s*([A-Z\"])/\. $1/g; # replace . **** Begin or . #### Begin or ) *The $text =~ s/\.\s*\([^\)]*\) ([A-Z])/\. $1/g; # . (blah blah) S... =&gt; . S... </code></pre> <p>As you can see, I'm dealing with nasty html and have to beat it into submission. </p> <p>I'm hoping there is a simpler, aesthetically appealing way to do this. I have about 50 lines that look just like what is above.</p> <p>I have solved one version of this problem by using a hash where the key is the comment, and the hash is the reg expression, like so:</p> <pre><code>%rxcheck = ( 'time of day'=&gt;'\d+:\d+', 'starts with capital letters then a capital word'=&gt;'^([A-Z]+\s)+[A-Z][a-z]', 'ends with a single capital letter'=&gt;'\b[A-Z]\.' } </code></pre> <p>And this is how I use it:</p> <pre><code> foreach my $key (keys %rxcheck) { if($snippet =~ /$rxcheck{ $key }/g){ blah blah } } </code></pre> <p>The problem comes up when I try my hand at a hash that where the key is the expression and it points to what I want to replace it with... and there is a $1 or $2 in it.</p> <pre><code>%rxcheck2 = ( '(\w) \"'=&gt;'$1\"' } </code></pre> <p>The above is to do this:</p> <pre><code>$snippet =~ s/(\w) \"/$1\"/g; </code></pre> <p>But I can't seem to pass the "$1" part into the regex literally (I think that's the right word... it seems the $1 is being interpreted even though I used ' marks.) So this results in:</p> <pre><code>if($snippet =~ /$key/$rxcheck2{ $key }/g){ } </code></pre> <p>And that doesn't work.</p> <p>So 2 questions:</p> <p>Easy: How do I handle large numbers of regex's in an easily editable way so I can change and add them without just cut and pasting the line before?</p> <p>Harder: How do I handle them using a hash (or array if I have, say, multiple pieces I want to include, like 1) part to search, 2) replacement 3) comment, 4) global/case insensitive modifiers), if that is in fact the easiest way to do this?</p> <p>Thanks for your help -</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload