use strict;
use warnings;
use feature qw(say);
use Babble::Match;

# Define what we want to match against.
my $match = Babble::Match->new(
  top_rule => 'Document',
  text     => q{
    for my $i (0..7) {
      say $i;
    }

    for my $j (@list) {
      say $j;
    }
  },
);

my @vars;
# Look up the definition of the PerlControlBlock rule in PPR::X:
$match->each_match_within( ControlBlock =>  [
  # Match either for or foreach blocks
  q{
    for(?:each)?+ \b
    (?>(?&PerlOWS))
  },
  # With a simple `my` declaration (full grammar supports
  # `my`/`our`/`state` here and some other syntax)
  q{
    (?> (?: my ) (?>(?&PerlOWS)) )?+
  },
  # Capture a scalar variable name into the `variable` submatch
  [ variable => '(?&PerlVariableScalar)' ],
  # Match the rest of the `for` block
  q{
    (?>(?&PerlOWS))
    (?> (?&PerlParenthesesList) | (?&PerlQuotelikeQW) )

    (?>(?&PerlOWS))
    (?>(?&PerlBlock))
  },
] => sub {
  my ($m) = @_;
  push @vars, $m->submatches->{variable}->text;
});

say "variables found: @vars";

__END__
variables found: $i $j
