Non-destructive Perl regex substitutions

Software

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

Me!

Ruben Schade is a technical writer and IaaS engineer in Sydney, Australia who refers to himself in the third person in bios. Wait, not BIOS… my brain should be EFI by now.

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

You can leave me a comment by contacting me, and I might publish your thoughts. Please read the FAQs first though.

If you found this post helpful or entertaining, you can shout me a coffee or buy some silly merch. Thanks!