I was recently reading through Perl Regular Expression Tutorial (perlretut) when I found the section on using the ‘r’ option. I’d seen this before but rarely had any reason to use it. Then it occurred to me that you could chain these together.

I’ve been programming Perl for 30+ years and don’t think I’ve ever seen this before.

Here’s an example that shows how I would usually do this, i.e. a series of var =~ s/// lines, and how to do the same thing in one line while initializing a variable.

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';

my $T = "one two trash THREE random";
my $T2 = $T;
$T2 =~ s/trash|random//g;
$T2 =~ s/(THREE)/lc($1)/e;
$T2 =~ s/\s+/ /g;
$T2 =~ s/^/Count with me: /;

my $T3 = $T =~ s/trash|random//gr =~ s/(THREE)/lc($1)/er =~ s/\s+/ /gr =~ s/^/Count with me: /r;

say "T  := $T\nT2 := $T2\nT3 := $T3";

Output:

$ ./perl-subst-test.pl 
T  := one two trash THREE random
T2 := Count with me: one two three 
T3 := Count with me: one two three 

Anyways, I had to tell someone …

  • zikal
    link
    fedilink
    English
    arrow-up
    3
    ·
    2 years ago

    I really like how easy it is to use regex in Perl with =~. I’ve always wondered why that’s not the case in Go and Rust where I need to compile the regex using non-std library.

    • umbraklat@lemmy.sdf.orgOP
      link
      fedilink
      English
      arrow-up
      2
      ·
      2 years ago

      Agreed. Though I’m very comfortable using RE, I’ve still never used it with backtracking or recursion. I always feel like I can go much deeper in Perl, though 99% of what I need to do doesn’t require it.

  • borup
    link
    fedilink
    English
    arrow-up
    2
    ·
    1 year ago

    Oh wow I’ve written Perl since 92-93. But I don’t think I’ve never seen nor user the r option. For grouped replacements like that I’ve tended to localise $_. Which is pretty much the only useful use of local I can think of.

  • yzh@lemm.ee
    link
    fedilink
    English
    arrow-up
    1
    ·
    1 year ago

    Non-destructive substitution was introduced in Perl 5.14 (released in 2011) so it’s not surprising you haven’t heard of it if you’ve been programming perl for years before that. Especially if you’re not always reading every single release announcement.

    Hanging out on the Perl Slack and Discord channels is fun because there’s always someone out there who drops one of these kind of obscure but incredibly useful features when someone asks for help.

    • umbraklat@lemmy.sdf.orgOP
      link
      fedilink
      English
      arrow-up
      1
      ·
      edit-2
      1 year ago

      Where do I find this slack and discord? asking for a friend…

      edit: I found “Perl Hideout” … is that one?