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

I have a series of template text (straight ascii, \w characters only) files with fields marked as %%field%%. Each field on a line will be unique but multiple fields may occur on a line. What regex can I use to list all the field names on a line? So far I have this working code but I'd be interested to see if there is a more general solution for n field names.
foreach (@fields) { m/%%(\w+?)%%.*%%(\w+?)%%/; push @matches, $1, $2; }

just another cpan module author

Replies are listed 'Best First'.
Re: regex: list each ocurrence of a pattern in a line
by ikegami (Patriarch) on Nov 19, 2008 at 11:28 UTC

    Meet the "g" modifier.

    my @matches; for (@fields) { push @matches, /%%(\w+?)%%/g; }
    Or even
    my @matches = map /%%(\w+?)%%/g, @fields;

    The "?" quantifier isn't necessary. I don't know if it's faster with or without it. If probably only matters if the elements of @fields are very long strings, so you might as well leave it out.

      Thanks, thats just what I needed, and a use for map too.

      just another cpan module author