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!


Imprint

This is one of about 5000 posts on Rubénerd. View the home page for the latest, or related posts also tagged with:

If you liked this post, feel free to buy me a coffee, leave me a comment on Twitter, or email me at weblog2017@rubenschade.com. Thanks :).