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

Hi, all. I think I'm in way over my head and could use your help.

I am trying to rewrite email alerts from one system so they can generate tickets in a different system. I thought I could get clever and create a template with field names that the program would fill in with values from the incoming email.

When the program encounters a string of the form %-Field Name-% it replaces it with the field with that name in the incoming email. So far, so good.

The problem is that some of the fields need to be trimmed or reformatted. I thought I could add some syntax--hugely ugly, I know--that would let me specify s/// substitutions in the template file, so that %-Incoming Port%%/dev/pts/%%Port Number-% would be read as Print the value of the "Port Number" field, but replace the string "/dev/pts/" with "on Port# ". ALSO working just fine, thankyouverymuch.

Or so I thought until I tried to use () and \1 in the template, anyway. %-Message Text%%.* for (.*) from .*%%\1-% (so that "successful login for root from blah blah" gets rewritten as "root") fails emphatically, miserably, repeatedly, as do I.

I've lost count of the number of things I've tried, but I've been googling, reading, and putzing for about 8 hours now and I'd dearly love a hint. I feel like it must be possible because this much seems to work:

$val=$envalert{$var}; if ($val =~ /$modfrom/) { $replval = $1 ;

When $modfrom contains ()'s, then $1 seems to get set properly. But I can't wrap my head around how to do the rest of the substitution. Any pointers will be gratefully received.

Replies are listed 'Best First'.
Re: Regex with variables
by AnomalousMonk (Archbishop) on Apr 25, 2011 at 21:30 UTC

    Quick hint: Text::Template. Take a look at this module and see if it may fulfill some, at least, of your needs.

      I suppose that was predictable. In fact, from the documentation for Text::Template...

      When people make a template module like this one, they almost always start by inventing a special syntax for substitutions. For example, they build it so that a string like %%VAR%% is replaced with the value of $VAR.

      Ha! I started using %-VAR-% after the second iteration. That's COMPLETELY different.

      Then they realize the need extra formatting, so they put in some special syntax for formatting. Then they need a loop, so they invent a loop syntax. Pretty soon they have a new little template language.

      Okay, so I hadn't gotten to the looping part. Anyway, it looks like Text::Template will do exactly what I need, better than I was going to do it, and I could have saved myself a day and a half if I had thought to look for it first. I honestly hope I am able to forgive you someday :-)

      Thanks for the quick and helpful reply.