in reply to Reading Regexes from File

You might want to explore using a hash with the regular expression as the key and the replacement text as the value. You can use compiled regular expressions as hash keys. You might need to consider using \Q and \E or quotemeta when compiling the regular expressions. In the script below I read the patterns and corresponding replacements from the DATA file at the end of the script and the patterns contain no spaces so a simple split on white space is sufficient. Your patterns may be more complex.

use strict; use warnings; my %substitutions = (); while ( <DATA> ) { chomp; my ($pattern, $replace) = split; my $rxPattern = qr{(?si)$pattern}; $substitutions{$rxPattern} = $replace; } my $str = q{a capital M and Fish}; print qq{$str\n}; $str =~ s{$_}{$substitutions{$_}} for keys %substitutions; print qq{$str\n}; __END__ \s*M\s* MALE \s*F\s* FEMALE

The output produced is

a capital M and Fish a capitalMALEandFEMALEish

I hope this is of use.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Reading Regexes from File
by jeffthewookiee (Sexton) on Apr 12, 2007 at 18:43 UTC
    OK, tried a slightly different approach. Still reading the regular expressions from file, but I'm using a :: to delimit the search pattern from the replacement text. Problem is, it's literally interpreting the replacement. For example this in the file:

    (\d{4})(\d{2})(\d{2})::$2-$3-$1

    When run this way in the code:

    my ($search, $replace) = split "::", $rule; $value =~ s/$search/$replace/si;

    Yields - $2-$3-$1

    I wanted it to refactor the date into a MM-DD-YYYY format.
      I don't think that is ever going to work, although more experienced Monks may know better. The method I described is only good for replacing a pattern with simple text. You are getting the literal $2-$3-$1 because the perl interpreter sees the scalar $replace when it parses your code and interpolates it's contents as a literal string rather than seeing the "magical to regular expressions" $1 etc. If you try to rectify things by eval'ing $replace, i.e $value =~ s/$search/eval "$replace"/sie then Perl interprets that as a sum and comes up with, for today's date, -2015.

      To do anything more fancy than a simple text replacement you will almost certainly have to take the eval approach suggested by duff and expanded on by ikegami.

      Cheers,

      JohnGG