mobiusinversion has asked for the wisdom of the Perl Monks concerning the following question:
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:use strict; my $my_name = "august ferdinand mobius"; $my_name =~ s/\b(\w)/\U$1/g; print $my_name; #prints August Ferdinand Mobius
I would like to call such a subroutine as follows:sub replace { my($text, $pattern, $replacement, $modifiers) = @_; (my $result = $text) =~ s/$pattern/$replacement/$modifiers; return $result; }
Of course, the above doesn't work. But I have tried many other ways, e.g. using eval, s///ge, s///gee, etc.$my_name = replace("august ferdinand mobius","\b(\w)","\U$1","igs");
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)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; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regex Substitution Evaluations
by pc88mxer (Vicar) on Jul 05, 2008 at 20:27 UTC | |
by mobiusinversion (Beadle) on Jul 05, 2008 at 20:34 UTC | |
by Your Mother (Archbishop) on Jul 05, 2008 at 20:51 UTC | |
by oko1 (Deacon) on Jul 05, 2008 at 22:31 UTC | |
by mobiusinversion (Beadle) on Jul 07, 2008 at 18:53 UTC | |
|
Re: Regex Substitution Evaluations
by ikegami (Patriarch) on Jul 05, 2008 at 23:41 UTC |