in reply to while-loop regex substitution with 'g' option

Just for fun, here's a case where a loop is still needed for s///g

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11159009 use warnings; use v5.36; #my $x = "xyzzy foo1 foo2"; my $x = "xxxxxyyyyyyyyxxxyyy"; my @captured; while ($x =~ s{ (xy) }{}msxg) { push @captured, $1; say "To Go '$x'"; } say "Captured: '$_'" for @captured; say "Left with '$x'";

Outputs:

To Go 'xxxxyyyyyyyxxyy' To Go 'xxxyyyyyyxy' To Go 'xxyyyyy' To Go 'xyyyy' To Go 'yyy' Captured: 'xy' Captured: 'xy' Captured: 'xy' Captured: 'xy' Captured: 'xy' Left with 'yyy'

Replies are listed 'Best First'.
Re^2: while-loop regex substitution with 'g' option
by ibm1620 (Hermit) on Apr 22, 2024 at 04:55 UTC
    Right. When the substitution can produce new matches, you need to restart the scan from the beginning. Strictly speaking, then, is /g needed? hm.