use HTML::Parser;
my $file = 'example.html';
my ($in_div,$in_wanted_div) = (0,0);
my @result;
my $parser = HTML::Parser->new(
api_version => 3,
start_h => [\&start, "tagname, attr"],
text_h => [\&text, "dtext"],
end_h => [\&end, "tagname"],
empty_element_tags => 1,
);
$parser->parse_file($file);
print join(', ',@result);
sub start {
my ($tag, $attr) = @_;
return unless ($tag eq 'div');
if (exists $attr->{'class'} and $attr->{'class'} eq 'data') {
$in_div = 1;
$in_wanted_div = 1;
push(@result, "$attr->{'id'}=");
}
else {
$in_div++;
}
}
sub text {
my ($text) = @_;
return unless $in_wanted_div;
$text =~ s/\W//g;
$result[-1] .= $text;
}
sub end {
my ($tag) = @_;
return unless ($tag eq 'div');
$in_div--;
$in_wanted_div = 0 if not $in_div;
}