in reply to Generating a list of lists (for HTML::Element) from trivial markup
I find it's easier to think in terms of "what list am I adding into currently?", and "what's the stack of lists I was adding to?". That 2nd question handles the possibility that start/end blocks are nested.
So here's what I came up with (but see jethro's answer below, his is much cleaner):
#!/usr/local/bin/perl use strict; use warnings; use Data::Dumper; $Data::Dumper::Indent = 1; my @lines = <DATA>; chomp @lines; my @list = ([q{div}, {id => q{article}}]); my $currentList_r = \@{$list[0]}; my $currentDiv=""; my @listStack; LINE: for my $line (@lines){ chomp $line; if($line=~/^;([^;]+)_start;$/) { $currentDiv=$1; my $divList_r=['div',{class=>$1}]; push @listStack, $currentList_r; $currentList_r=$divList_r; next LINE; } if($line=~/^;([^;]+)_end;$/) { die "Tag mismatch between start ($currentDiv) and end ($1)" unless $1 eq $currentDiv; $currentDiv=""; die "end with no matching start!" unless scalar @listStack; push @{$listStack[-1]}, $currentList_r; $currentList_r = pop @listStack; next LINE; } my ($tag, $txt) = $line =~ /^;([^;]+);(.*)/; push @{$currentList_r}, [$tag, $txt]; } print Dumper(\@list), __DATA__ ;p;one ;greybox_start; ;h2;two ;greybox_end; ;p;three
|
|---|