Non-destructive Perl regex substitutions


I’ve been a Perl Monk in training for years, but I only just realised this.

Say you want to print an original string, and a modified version with a case-insensitive substitution. This below will output “shimapan shima-melonpan”, just because I can.

my $first = "shimapan"
my $second = $first;
$second =~ s/pan/-melonpan/i;
print("$first $secondn");

You can use “r” instead to non-destructively substitute, with the same result.

my $first = "shimapan"
my $second = $first =~ s/pan/melonpan/ir;
print("$first $secondn");

I generally avoid Perl Golf-isms for the same reasosn Dagolden does, but in this case I find it does remove a little redundancy, and is just as readable.

Thanks to @damncabbage for getting me to finally post this!

Author bio and support


Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.