in reply to Re: Regexes loaded from file
in thread Regexes loaded from file

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 :)

Replies are listed 'Best First'.
Re: Re: Re: Regexes loaded from file
by Popcorn Dave (Abbot) on May 02, 2002 at 19:09 UTC
    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!

Re: Re: Re: Regexes loaded from file
by Anonymous Monk on May 02, 2002 at 18:31 UTC
    Some sort of <code>while(<>){push @subs,eval 'sub{local$_=shift;'.$_.';$_}'}<code>?
      This is correct but not maximally efficient. Why create a separate sub for each s///? It's more efficient to just build one sub containing all the substitutions. Also, why localize and return $_? Operating on it directly is more efficient. See my solution below for an example of what I'm talking about.

      -sam

        I hadn't seen it. And I assumed that he only wanted to read regexes from a file. There it would be more usefull to have them separated. Of course your solution is better in the special situation the whole thread is about. However I read only the note to which I replied. So I chose the more general solution.