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

Dear Monks,

my $phrases='regulate each other|each other|regulate|in cells';

my $sentence='A and B regulate each other in cells';

Desired output: 'A and B %regulate_each_other% in_cells'. That is tag the phrases in the sentence (as complete phrases not partial) and also fill the spaces within the tagged phrases with underscores if there are spaces in the pattern.

While I could achieve the tagging part as below, I am not sure how the spaces within the phrases can be filled with undescores. Any good way of doing this?

$sentence =~ s/($phrases)/\%$1\%/ig;

Thanks a lot.

Replies are listed 'Best First'.
Re: within pattern manipulation
by johngg (Canon) on Sep 18, 2009 at 15:08 UTC
    Desired output: 'A and B %regulate_each_other% in_cells'.

    Shouldn't that be: 'A and B %regulate_each_other% %in_cells%'? That is what ikegami's solution produces.

    Cheers,

    JohnGG

Re: within pattern manipulation
by jwkrahn (Abbot) on Sep 18, 2009 at 14:09 UTC
    $sentence =~ s{ ( $phrases ) }{ ( my $string = $1 ) =~ tr/ /_/; "%$str +ing%" }xieg;
      Thanks jwkrahn for the reply. However, it is not producing the desired output. The output I am getting is:

      A and B %regulate% each other in cells

        By using "x", he changed the meaning of the spaces in your pattern. Fixed:
        $sentence =~ s{($phrases)}{ ( my $string = $1 ) =~ tr/ /_/; "%$string%" }ieg;