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

I want to create file containing a set of substitutions, one per line of the form s/foo/bar/g. I then want to load these substs from the file and apply to an arbitrary set of strings (loaded from a different file) to transform them.

Any ideas :)

Replies are listed 'Best First'.
Re: Regexes loaded from file
by samtregar (Abbot) on May 02, 2002 at 18:05 UTC
    #!/usr/bin/perl -w open SUBS, "subs.txt" or die; my $sub = eval "sub { " . join('', <SUBS>) . "}"; die "Unable to complile subs.txt : $@" if $@; close SUBS; open STRINGS, "strings.txt" or die; while(<STRINGS>) { &$sub; print; } close STRINGS;

    -sam

      Now why would this get downvoted? That's a working, efficient, tested solution to the problem posted! What do you want, a dance routine to go along with it?

      -sam

        Don't worry Sam... I thought this was a neat piece of code u put and it does exactyl what I asked. Nice one :)
Re: Regexes loaded from file
by Popcorn Dave (Abbot) on May 02, 2002 at 17:57 UTC
    Seems easy enought to do. Open the file of regexes, open the file you want to change, then read a line from both files, do your substitution and write it.

    My question is: Why you'd want to do this? Homework assignment?

      No not homework - needed for felxible processing of a set of metabolite reaction equations. Its not as simple as you allude becuase you need either to use closures or subroutine refs... I just wondered if anyone knew how. Cheers :)
        Sorry, thought it sounded simpler than it was. :)

        However I did do something similar myself not too long ago for a program I wrote. This was for a regular expression tutor I wrote ( which I hope to post to craft as soon as I iron out one blasted bug ) so hopefully this will prove useful to you.

        =head2 If we've had a regular expression with grouping, we need to sho +w the matches we made there too. Unless we count the number of matchi +ng parens, which could get odd if there was a match looking for '( +' and ')', we run a simple counter and check if the match variable exists. + If it does, we print it out. If no parenthesis are used, $match_resul +ts holds our match. =cut {eval "\@matches = (\$user_text =~ $regex); \$match_results .= +\$&;"; $match_results .= "\n"; $match_results .= " Variables:\n"if defined($matches[$i]) +; for (my $i = 1; $i <= @matches; $i++) { my $found = $matches[$i - 1]; $match_results .= " \$$i:$found \n" if defined($matc +hes[$i]); } } # end eval block } # end if substr eq 'm'

        This does encompass multiple matches on an m//. The s// and tr// I did like: eval "\$match_results =~ $regex

        Of course I did have the help of some here to pull this stunt off :)

        Good luck!

        Some sort of <code>while(<>){push @subs,eval 'sub{local$_=shift;'.$_.';$_}'}<code>?