Slide 42
Slide 42 text
Perl5 nested structure
#! /usr/bin/env perl
use 5.010;
# We're going to need this to extract hierarchical data structures...
our @stack = [];
my $LIST = qr{
# Match this...
(?&NESTED)
# Which is defined as...
(?(DEFINE)
(?
# Keep track of recursions on a stack...
(?{ local @::stack = (@::stack, []); })
# Match a list of items...
\[ \s* (?>
(?&ITEM)
(?:
\s* , \s* (?&ITEM)
)*+
)? \s*
\]
# Pop the stack and add that frame to the growing data structure...
(?{ local @::stack = @::stack;
my $nested = pop @stack;
push @{$::stack[-1]}, $nested;
})
)
# For each item, push it onto the stack if it's a leaf node...
(?
(\d+) (?{ push @{$stack[-1]}, $^N })
| (?&NESTED)
)
)
}x;
# Match, extracting a data structure...
'[1,2,[3,3,[4,4]],5]' =~ /$LIST/;
# Retrieve the data structure...
my $parse_tree = pop @stack;
# Show it...
use Data::Dumper 'Dumper';
say Dumper($parse_tree);