home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / share / doc / libhtml-parser-perl / examples / hanchors next >
Encoding:
Text File  |  2001-03-26  |  1.1 KB  |  47 lines

  1. #!/usr/bin/perl -w
  2.  
  3. # This program will print out all <a href=".."> links in a
  4. # document together with the text that goes with it.
  5.  
  6. use HTML::Parser;
  7.  
  8. my $p = HTML::Parser->new(api_version => 3,
  9.      start_h => [\&a_start_handler, "self,tagname,attr"],
  10.      report_tags => [qw(a img)],
  11.     );
  12. $p->parse_file(shift || die) || die $!;
  13.  
  14. sub a_start_handler
  15. {
  16.     my($self, $tag, $attr) = @_;
  17.     return unless $tag eq "a";
  18.     return unless exists $attr->{href};
  19.     print "A $attr->{href}\n";
  20.  
  21.     $self->handler(text  => [], '@{dtext}' );
  22.     $self->handler(start => \&img_handler);
  23.     $self->handler(end   => \&a_end_handler, "self,tagname");
  24. }
  25.  
  26. sub img_handler
  27. {
  28.     my($self, $tag, $attr) = @_;
  29.     return unless $tag eq "img";
  30.     push(@{$self->handler("text")}, $attr->{alt} || "[IMG]");
  31. }
  32.  
  33. sub a_end_handler
  34. {
  35.     my($self, $tag) = @_;
  36.     my $text = join("", @{$self->handler("text")});
  37.     $text =~ s/^\s+//;
  38.     $text =~ s/\s+$//;
  39.     $text =~ s/\s+/ /g;
  40.     print "T $text\n";
  41.  
  42.     $self->handler("text", undef);
  43.     $self->handler("start", \&a_start_handler);
  44.     $self->handler("end", undef);
  45. }
  46.  
  47.