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

Dear monks If I have a function foo(),
sub foo {my $c = shift; $c*=5; return $c;}
All those substitutions works as expected:
$bar =~ s/(\d{2})/joo/msg; $bar =~ s#(\d{2})#jee#msg; $bar =~ s#(\d{2})#foo($1)#mesg; $bar =~ s#(\d{2})#<td>ha ha ha</td>#msg;
But if want to use all things: a /e modifier, html tags and # instead of / (because \-escaped slashes are not very readable)
$bar =~ s#(\d{2})#<td>foo($1)</td>#mesg;
I only get
Bareword found where operator expected at a.pl line 18, near "<td>foo" (Missing operator before foo?) syntax error at a.pl line 18, near "<td>foo" Search pattern not terminated at a.pl line 18.
man perlop is not very helpful.
Any non-whitespace delimiter may replace the slashes. Add space after the "s" when using a character allowed in identifiers. If single quotes are used, no interpretation is done on the replacement string (the "/e" modifier overrides this, however). Note that Perl treats backticks as normal delimiters; the replacement text is not evaluated as a command. If the PATTERN is delimited by bracketing quotes, the REPLACEMENT has its own pair of quotes, which may or may not be bracketing quotes, for example, s(foo)(bar) or s<foo>/bar/. A /e will cause the replacement portion to be treated as a full-fledged Perl expression and evaluated right then and there. It is, however, syntax checked at compile-time. A second "e" modifier will cause the replacement portion to be "eval"ed before being run as a Perl expression.
Tested in Debian Jessie (5.20) and in Debian Buster (5.29).

Replies are listed 'Best First'.
Re: Side effects of an /e modifier
by Corion (Patriarch) on Jan 29, 2020 at 14:13 UTC

    I think the right hand side in an s///e block must be valid Perl. <td>foo($1)</td> is not valid Perl.

    Quoting the HTML tags should work:

    $bar =~ s#(\d{2})#"<td>".foo($1)."</td>"#mesg;

    More code:

    #!perl -w sub foo { "<$_[0]>" }; my $bar = '2299-33-ff'; $bar =~ s#(\d{2})#"<td>".foo($1)."</td>"#mesg; print $bar; __END__ <td><22></td><td><99></td>-<td><33></td>-ff
Re: Side effects of an /e modifier
by hippo (Archbishop) on Jan 29, 2020 at 14:11 UTC

    <td>foo($1)</td> is not a valid expression in Perl. Maybe try '<td>' . foo($1) . '</td>' instead?

Re: Side effects of an /e modifier
by k-mx (Scribe) on Jan 29, 2020 at 17:17 UTC

    Yet another solution (:

    You can eval random code inside (?{ }) and use result with variable $^R

    $bar =~ s#\d{2}(?{ $& * 5})#<td>$^R</td>#gms;

    More information:

    perldoc -v '$^R' perldoc -v '$&' perldoc perlre

    And I want to point, that you don't need to capture whole match. It will already situated in $&

    P.S.

    I should have said, that there is global performance penalty for using $& somewhere in your code. It was fixed only in 5.020

    Please read following documentation for more information:

    perldoc perlfaq6 perldoc perlvar