#!/usr/bin/env perl use v5.36; my $x = "xyzzy foo1 foo2"; my @captured; while ($x =~ s{ \s* (foo\w) \s* }{}msxg) { push @captured, $1; } say "Captured: '$_'" for @captured; say "Left with '$x'";