Dearest Monks,

Please consider the following code:
use strict; my $my_name = "august ferdinand mobius"; $my_name =~ s/\b(\w)/\U$1/g; print $my_name; #prints August Ferdinand Mobius
I am trying to create a subroutine that consumes a string, a pattern, a replacement and a modifier (perhaps limited to one or more of 'igsx') and returns the result of a substitution:
sub replace { my($text, $pattern, $replacement, $modifiers) = @_; (my $result = $text) =~ s/$pattern/$replacement/$modifiers; return $result; }
I would like to call such a subroutine as follows:
$my_name = replace("august ferdinand mobius","\b(\w)","\U$1","igs");
Of course, the above doesn't work. But I have tried many other ways, e.g. using eval, s///ge, s///gee, etc.

I have attempted to do my homework using the Owl, Camel and Ram books, plus the perldoc, but I am totally stumped. Any help would be greatly appreciated.

Update: 13:06 PST
This appears to work:
use strict; my $x = "august ferdinand mobius"; my $y = replace($x, '\b(\w)', '\U$1', 'igs'); print $y; sub replace { my($text, $pattern, $replacement, $modifiers) = @_; my $result = ''; eval '($result = $text)'."=~ s/$pattern/$replacement/$modifiers"; return $result; }
It does however, to my mind, open security problems due to the eval'ing - which I hope is unnecessary with a more elegant solution. Besides security, will this fail on certain edge cases? (besides non-escaped members of the dirty dozen, which I'm handling now)

In reply to Regex Substitution Evaluations by mobiusinversion

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.