The problem has nothing to do with map.

First of all, you store the pattern in $string, but you use $phrase in the substitution. I think the code you posted isn't the code you actually used.

The first part of the problem you mention is that you want to match the space between "foo" and "bar" in " foo bar" twice. If that was it, you could use (?=) and/or (?<=) to solve the problem.

However, you also want to replace that space twice. I don't see how you can do that entirely in one substitution.

One simple solution is to do a prep pass to double up the space:

my @phrases = qw( foo bar ); my $sentence = " foo bar "; my ($phrases_pat) = map qr/$_/, join '|', map quotemeta, @phrases; $sentence =~ s/($phrases_pat)(\s)($phrases_pat)/$1$2$2$3/g; $sentence =~ s/(\s$phrases_pat\s)/#$1#/g; print("$sentence\n"); # "# foo ## bar #"

Or maybe you want

... $sentence =~ s/($phrases_pat)(\s)($phrases_pat)/$1$2$2$3/g; $sentence =~ s/\s($phrases_pat)\s/#$1#/g; print("$sentence\n"); # "#foo##bar#"

If you consider the start and end of the string to be equivalent to spaces, you'll need to handle those specially.


In reply to Re: map function use by ikegami
in thread map function use by newbio

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.