#!/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'"; #### 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'