my $string = 'foobarfoo'; { my $hit; my $regex = qr/(foo)(bar)(?{ $hit = $^N })(foo)/; print $hit if $string =~ m/$regex/; }