Thread [HTML::Parser] Überschriften parsen und als Liste darstellen - nur wie? (6 answers)
Opened by GwenDragon at 2023-12-20 16:08

GwenDragon
 2023-12-21 09:56
#195712 #195712
User since
2005-01-17
14607 Artikel
Admin1
[Homepage]
user image
Ein Flag, ob sich der Parser ein Heading geschnappt hatte, ist da wohl die Lösung.
Danke.

Code: (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
sub toc {
my $source = shift;

my @parsed;
my $h_flag;
my $data;

my $text_sub = sub {
if ($h_flag) {
$data->{text} = shift;
push @parsed, $data;
$data = undef;
$h_flag = 0;
}
};

## my $end_sub = sub {
## if ($h_flag) {
## $data = undef;
## $h_flag = 0;
## }
## };

my $tag_sub = sub {
my $s = shift;
my $tag = shift;
my $self = shift;

if ( $tag =~ m/[hH](\d)/ ) {
$data = { level => $1, tag => $tag, text => "" };
$h_flag = 1;
}
};

# HTML-Parser erzeugen
my $p = HTML::Parser->new(
api_version => 3,
start_h => [ $tag_sub, "text,tagname,self" ],
#end_h => [ $end_sub, "text,tagname,self" ],
text_h => [ $text_sub, "text,self" ],
#process_h => [ $text_sub, "text,self" ],
#comment_h => [ $text_sub, "text,self" ],
#declaration_h => [ $text_sub, "text,self" ],
#default_h => [ $text_sub, "text,self" ],
);
$p->empty_element_tags(1);
$p->report_tags(qw(h1 h2 h3 h4 h5 h6));
$p->xml_pic(1);
$p->utf8_mode(1);
$p->case_sensitive(1);
$p->parse($source);
$p->eof();

return @parsed;

} ## end sub toc


Damit ist meine Ausgangsfrage beatwortet.
Last edited: 2023-12-21 11:29:27 +0100 (CET)

View full thread [HTML::Parser] Überschriften parsen und als Liste darstellen - nur wie?