I came across a function today that made me stop and think. I can't think of a good reason to do it:
sub replace_string {
my $string = shift;
my $regex = shift;
my $replace = shift;
$string =~ s/$regex/$replace/gi;
return $string;
}
The only possible value I can see to this is that it gives you the ability to control the default options used with a substitution, but I don't consider that useful. My first reaction upon seeing this function get called is "what does this do?". Once I learn what it does, I am going to assume it does that from that point on. Which means if it changes, it will break any of my code that needs it to do that. This means the function will likely never change, or changing it will break lots of code.
Right now I want to track down the original programmer and beat some sense into him or her. Is this a valid desire, or am I missing some value this function brings to the table?
The problems with that function include:
replace_string
doesn't tell you that you're doing a case-insensitive, global replace without escaping.$string =~ s{$this}{$that}gi
is something you can learn what it means once, and its not like its some weird corner feature. replace_string
everyone has to learn the details of, and its going to be different for everyone who writes it.qr//
but that's far more advanced knowledge than the s///
its hiding.The advantages are:
g
and i
defaults are always there (but that's non-obvious from the name).s{}{}
is difficult).$1
, $+
, etc...) but they're automatically locally scoped to the function. They won't interfere if you're making use of them for another regex.A little overzealous with the encapsulation.
print replace_string("some/path", "/", ":");
Yes, you get some magic in not having to replace / with a different delimiter or escape / in the regex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With