home *** CD-ROM | disk | FTP | other *** search
/ Australian Personal Computer 2004 July / APC0407D2.iso / workshop / apache / files / ActivePerl-5.6.1.638-MSWin32-x86.msi / _76acb2466bb3cc86afd9bfe8a21d1dde < prev    next >
Encoding:
Text File  |  2004-04-13  |  35.6 KB  |  1,142 lines

  1. package HTML::Parser;
  2.  
  3. # Copyright 1996-2004, Gisle Aas.
  4. # Copyright 1999-2000, Michael A. Chase.
  5. #
  6. # This library is free software; you can redistribute it and/or
  7. # modify it under the same terms as Perl itself.
  8.  
  9. use strict;
  10. use vars qw($VERSION @ISA);
  11.  
  12. $VERSION = '3.36';  # $Date: 2004/04/01 12:05:52 $
  13.  
  14. require HTML::Entities;
  15.  
  16. require DynaLoader;
  17. @ISA=qw(DynaLoader);
  18. HTML::Parser->bootstrap($VERSION);
  19.  
  20.  
  21. sub new
  22. {
  23.     my $class = shift;
  24.     my $self = bless {}, $class;
  25.     return $self->init(@_);
  26. }
  27.  
  28.  
  29. sub init
  30. {
  31.     my $self = shift;
  32.     $self->_alloc_pstate;
  33.  
  34.     my %arg = @_;
  35.     my $api_version = delete $arg{api_version} || (@_ ? 3 : 2);
  36.     if ($api_version >= 4) {
  37.     require Carp;
  38.     Carp::croak("API version $api_version not supported " .
  39.             "by HTML::Parser $VERSION");
  40.     }
  41.  
  42.     if ($api_version < 3) {
  43.     # Set up method callbacks compatible with HTML-Parser-2.xx
  44.     $self->handler(text    => "text",    "self,text,is_cdata");
  45.     $self->handler(end     => "end",     "self,tagname,text");
  46.     $self->handler(process => "process", "self,token0,text");
  47.     $self->handler(start   => "start",
  48.                           "self,tagname,attr,attrseq,text");
  49.  
  50.     $self->handler(comment =>
  51.                sub {
  52.                my($self, $tokens) = @_;
  53.                for (@$tokens) {
  54.                    $self->comment($_);
  55.                }
  56.                }, "self,tokens");
  57.  
  58.     $self->handler(declaration =>
  59.                sub {
  60.                my $self = shift;
  61.                $self->declaration(substr($_[0], 2, -1));
  62.                }, "self,text");
  63.     }
  64.  
  65.     if (my $h = delete $arg{handlers}) {
  66.     $h = {@$h} if ref($h) eq "ARRAY";
  67.     while (my($event, $cb) = each %$h) {
  68.         $self->handler($event => @$cb);
  69.     }
  70.     }
  71.  
  72.     # In the end we try to assume plain attribute or handler
  73.     while (my($option, $val) = each %arg) {
  74.     if ($option =~ /^(\w+)_h$/) {
  75.         $self->handler($1 => @$val);
  76.     }
  77.         elsif ($option =~ /^(text|start|end|process|declaration|comment)$/) {
  78.         require Carp;
  79.         Carp::croak("Bad constructor option '$option'");
  80.         }
  81.     else {
  82.         $self->$option($val);
  83.     }
  84.     }
  85.  
  86.     return $self;
  87. }
  88.  
  89.  
  90. sub parse_file
  91. {
  92.     my($self, $file) = @_;
  93.     my $opened;
  94.     if (!ref($file) && ref(\$file) ne "GLOB") {
  95.         # Assume $file is a filename
  96.         local(*F);
  97.         open(F, $file) || return undef;
  98.     binmode(F);  # should we? good for byte counts
  99.         $opened++;
  100.         $file = *F;
  101.     }
  102.     my $chunk = '';
  103.     while (read($file, $chunk, 512)) {
  104.     $self->parse($chunk) || last;
  105.     }
  106.     close($file) if $opened;
  107.     $self->eof;
  108. }
  109.  
  110.  
  111. sub netscape_buggy_comment  # legacy
  112. {
  113.     my $self = shift;
  114.     require Carp;
  115.     Carp::carp("netscape_buggy_comment() is deprecated.  " .
  116.            "Please use the strict_comment() method instead");
  117.     my $old = !$self->strict_comment;
  118.     $self->strict_comment(!shift) if @_;
  119.     return $old;
  120. }
  121.  
  122. # set up method stubs
  123. sub text { }
  124. *start       = \&text;
  125. *end         = \&text;
  126. *comment     = \&text;
  127. *declaration = \&text;
  128. *process     = \&text;
  129.  
  130. 1;
  131.  
  132. __END__
  133.  
  134.  
  135. =head1 NAME
  136.  
  137. HTML::Parser - HTML parser class
  138.  
  139. =head1 SYNOPSIS
  140.  
  141.  use HTML::Parser ();
  142.  
  143.  # Create parser object
  144.  $p = HTML::Parser->new( api_version => 3,
  145.                          start_h => [\&start, "tagname, attr"],
  146.                          end_h   => [\&end,   "tagname"],
  147.                          marked_sections => 1,
  148.                        );
  149.  
  150.  # Parse document text chunk by chunk
  151.  $p->parse($chunk1);
  152.  $p->parse($chunk2);
  153.  #...
  154.  $p->eof;                 # signal end of document
  155.  
  156.  # Parse directly from file
  157.  $p->parse_file("foo.html");
  158.  # or
  159.  open(F, "foo.html") || die;
  160.  $p->parse_file(*F);
  161.  
  162. HTML::Parser version 2 style subclassing and method callbacks:
  163.  
  164.  {
  165.     package MyParser;
  166.     use base 'HTML::Parser';
  167.  
  168.     sub start {
  169.        my($self, $tagname, $attr, $attrseq, $origtext) = @_;
  170.        #...
  171.     }
  172.  
  173.     sub end {
  174.     my($self, $tagname, $origtext) = @_;
  175.     #...
  176.     }
  177.  
  178.     sub text {
  179.     my($self, $origtext, $is_cdata) = @_;
  180.     #...
  181.     }
  182.  }
  183.  
  184.  my $p = MyParser->new;
  185.  $p->parse_file("foo.html");
  186.  
  187. =head1 DESCRIPTION
  188.  
  189. Objects of the C<HTML::Parser> class will recognize markup and
  190. separate it from plain text (alias data content) in HTML
  191. documents.  As different kinds of markup and text are recognized, the
  192. corresponding event handlers are invoked.
  193.  
  194. C<HTML::Parser> is not a generic SGML parser.  We have tried to
  195. make it able to deal with the HTML that is actually "out there", and
  196. it normally parses as closely as possible to the way the popular web
  197. browsers do it instead of strictly following one of the many HTML
  198. specifications from W3C.  Where there is disagreement, there is often
  199. an option that you can enable to get the official behaviour.
  200.  
  201. The document to be parsed may be supplied in arbitrary chunks.  This
  202. makes on-the-fly parsing as documents are received from the network
  203. possible.
  204.  
  205. If event driven parsing does not feel right for your application, you
  206. might want to use C<HTML::PullParser>.  This is an C<HTML::Parser>
  207. subclass that allows a more conventional program structure.
  208.  
  209.  
  210. =head1 METHODS
  211.  
  212. The following method is used to construct a new C<HTML::Parser> object:
  213.  
  214. =over
  215.  
  216. =item $p = HTML::Parser->new( %options_and_handlers )
  217.  
  218. This class method creates a new C<HTML::Parser> object and
  219. returns it.  Key/value argument pairs may be provided to assign event
  220. handlers or initialize parser options.  The handlers and parser
  221. options can also be set or modified later by the method calls described below.
  222.  
  223. If a top level key is in the form "<event>_h" (e.g., "text_h") then it
  224. assigns a handler to that event, otherwise it initializes a parser
  225. option. The event handler specification value must be an array
  226. reference.  Multiple handlers may also be assigned with the 'handlers
  227. => [%handlers]' option.  See examples below.
  228.  
  229. If new() is called without any arguments, it will create a parser that
  230. uses callback methods compatible with version 2 of C<HTML::Parser>.
  231. See the section on "version 2 compatibility" below for details.
  232.  
  233. The special constructor option 'api_version => 2' can be used to
  234. initialize version 2 callbacks while still setting other options and
  235. handlers.  The 'api_version => 3' option can be used if you don't want
  236. to set any options and don't want to fall back to v2 compatible
  237. mode.
  238.  
  239. Examples:
  240.  
  241.  $p = HTML::Parser->new(api_version => 3,
  242.                         text_h => [ sub {...}, "dtext" ]);
  243.  
  244. This creates a new parser object with a text event handler subroutine
  245. that receives the original text with general entities decoded.
  246.  
  247.  $p = HTML::Parser->new(api_version => 3,
  248.             start_h => [ 'my_start', "self,tokens" ]);
  249.  
  250. This creates a new parser object with a start event handler method
  251. that receives the $p and the tokens array.
  252.  
  253.  $p = HTML::Parser->new(api_version => 3,
  254.                 handlers => { text => [\@array, "event,text"],
  255.                                       comment => [\@array, "event,text"],
  256.                                     });
  257.  
  258. This creates a new parser object that stores the event type and the
  259. original text in @array for text and comment events.
  260.  
  261. =back
  262.  
  263. The following methods feed the HTML document
  264. to the C<HTML::Parser> object:
  265.  
  266. =over
  267.  
  268. =item $p->parse( $string )
  269.  
  270. Parse $string as the next chunk of the HTML document.  The return
  271. value is normally a reference to the parser object (i.e. $p).
  272. Handlers invoked should not attempt to modify the $string in-place until
  273. $p->parse returns.
  274.  
  275. If an invoked event handler aborts parsing by calling $p->eof, then
  276. $p->parse() will return a FALSE value.
  277.  
  278. =item $p->parse( $code_ref )
  279.  
  280. If a code reference is passed as the argument to be parsed, then the
  281. chunks to be parsed are obtained by invoking this function repeatedly.
  282. Parsing continues until the function returns an empty (or undefined)
  283. result.  When this happens $p->eof is automatically signalled.
  284.  
  285. Parsing will also abort if one of the event handlers calls $p->eof.
  286.  
  287. The effect of this is the same as:
  288.  
  289.  while (1) {
  290.     my $chunk = &$code_ref();
  291.     if (!defined($chunk) || !length($chunk)) {
  292.         $p->eof;
  293.         return $p;
  294.     }
  295.     $p->parse($chunk) || return undef;
  296.  }
  297.  
  298. But it is more efficient as this loop runs internally in XS code.
  299.  
  300. =item $p->parse_file( $file )
  301.  
  302. Parse text directly from a file.  The $file argument can be a
  303. filename, an open file handle, or a reference to an open file
  304. handle.
  305.  
  306. If $file contains a filename and the file can't be opened, then the
  307. method returns an undefined value and $! tells why it failed.
  308. Otherwise the return value is a reference to the parser object.
  309.  
  310. If a file handle is passed as the $file argument, then the file will
  311. normally be read until EOF, but not closed.
  312.  
  313. If an invoked event handler aborts parsing by calling $p->eof,
  314. then $p->parse_file() may not have read the entire file.
  315.  
  316. On systems with multi-byte line terminators, the values passed for the
  317. offset and length argspecs may be too low if parse_file() is called on
  318. a file handle that is not in binary mode.
  319.  
  320. If a filename is passed in, then parse_file() will open the file in
  321. binary mode.
  322.  
  323. =item $p->eof
  324.  
  325. Signals the end of the HTML document.  Calling the $p->eof method
  326. outside a handler callback will flush any remaining buffered text
  327. (which triggers the C<text> event if there is any remaining text).
  328.  
  329. Calling $p->eof inside a handler will terminate parsing at that point
  330. and cause $p->parse to return a FALSE value.  This also terminates
  331. parsing by $p->parse_file().
  332.  
  333. After $p->eof has been called, the parse() and parse_file() methods
  334. can be invoked to feed new documents with the parser object.
  335.  
  336. The return value from eof() is a reference to the parser object.
  337.  
  338. =back
  339.  
  340.  
  341. Most parser options are controlled by boolean attributes.
  342. Each boolean attribute is enabled by calling the corresponding method
  343. with a TRUE argument and disabled with a FALSE argument.  The
  344. attribute value is left unchanged if no argument is given.  The return
  345. value from each method is the old attribute value.
  346.  
  347. Methods that can be used to get and/or set parser options are:
  348.  
  349. =over
  350.  
  351. =item $p->strict_comment
  352.  
  353. =item $p->strict_comment( $bool )
  354.  
  355. By default, comments are terminated by the first occurrence of "-->".
  356. This is the behaviour of most popular browsers (like Mozilla, Opera and
  357. MSIE), but it is not correct according to the official HTML
  358. standard.  Officially, you need an even number of "--" tokens before
  359. the closing ">" is recognized and there may not be anything but
  360. whitespace between an even and an odd "--".
  361.  
  362. The official behaviour is enabled by enabling this attribute.
  363.  
  364. Enabling of 'strict_comment' also disables recognizing these forms as
  365. comments:
  366.  
  367.   </ comment>
  368.   <! comment>
  369.  
  370.  
  371. =item $p->strict_names
  372.  
  373. =item $p->strict_names( $bool )
  374.  
  375. By default, almost anything is allowed in tag and attribute names.
  376. This is the behaviour of most popular browsers and allows us to parse
  377. some broken tags with invalid attribute values like:
  378.  
  379.    <IMG SRC=newprevlstGr.gif ALT=[PREV LIST] BORDER=0>
  380.  
  381. By default, "LIST]" is parsed as a boolean attribute, not as
  382. part of the ALT value as was clearly intended.  This is also what
  383. Mozilla sees.
  384.  
  385. The official behaviour is enabled by enabling this attribute.  If
  386. enabled, it will cause the tag above to be reported as text
  387. since "LIST]" is not a legal attribute name.
  388.  
  389. =item $p->strict_end
  390.  
  391. =item $p->strict_end( $bool )
  392.  
  393. By default, attributes and other junk are allowed to be present on end tags in a
  394. manner that emulates MSIE's behaviour.
  395.  
  396. The official behaviour is enabled with this attribute.  If enabled,
  397. only whitespace is allowed between the tagname and the final ">".
  398.  
  399. =item $p->boolean_attribute_value( $val )
  400.  
  401. This method sets the value reported for boolean attributes inside HTML
  402. start tags.  By default, the name of the attribute is also used as its
  403. value.  This affects the values reported for C<tokens> and C<attr>
  404. argspecs.
  405.  
  406. =item $p->xml_mode
  407.  
  408. =item $p->xml_mode( $bool )
  409.  
  410. Enabling this attribute changes the parser to allow some XML
  411. constructs such as I<empty element tags> and I<XML processing
  412. instructions>.  It disables forcing tag and attribute names to lower
  413. case when they are reported by the C<tagname> and C<attr> argspecs,
  414. and suppresses special treatment of elements that are parsed as CDATA
  415. for HTML.
  416.  
  417. I<Empty element tags> look like start tags, but end with the character
  418. sequence "/>".  When recognized by C<HTML::Parser> they cause an
  419. artificial end event in addition to the start event.  The C<text> for
  420. the artificial end event will be empty and the C<tokenpos> array will
  421. be undefined even though the only element in the token array will have
  422. the correct tag name.
  423.  
  424. I<XML processing instructions> are terminated by "?>" instead of a
  425. simple ">" as is the case for HTML.
  426.  
  427. =item $p->unbroken_text
  428.  
  429. =item $p->unbroken_text( $bool )
  430.  
  431. By default, blocks of text are given to the text handler as soon as
  432. possible (but the parser takes care always to break text at a
  433. boundary between whitespace and non-whitespace so single words and
  434. entities can always be decoded safely).  This might create breaks that
  435. make it hard to do transformations on the text. When this attribute is
  436. enabled, blocks of text are always reported in one piece.  This will
  437. delay the text event until the following (non-text) event has been
  438. recognized by the parser.
  439.  
  440. Note that the C<offset> argspec will give you the offset of the first
  441. segment of text and C<length> is the combined length of the segments.
  442. Since there might be ignored tags in between, these numbers can't be
  443. used to directly index in the original document file.
  444.  
  445. =item $p->marked_sections
  446.  
  447. =item $p->marked_sections( $bool )
  448.  
  449. By default, section markings like <![CDATA[...]]> are treated like
  450. ordinary text.  When this attribute is enabled section markings are
  451. honoured.
  452.  
  453. There are currently no events associated with the marked section
  454. markup, but the text can be returned as C<skipped_text>.
  455.  
  456. =item $p->attr_encoded
  457.  
  458. =item $p->attr_encoded( $bool )
  459.  
  460. By default, the C<attr> and C<@attr> argspecs will have general
  461. entities for attribute values decoded.  Enabling this attribute leaves
  462. entities alone.
  463.  
  464. =item $p->case_sensitive
  465.  
  466. =item $p->case_sensitive( $bool )
  467.  
  468. By default, tagnames and attribute names are down-cased.  Enabling this
  469. attribute leaves them as found in the HTML source document.
  470.  
  471. =back
  472.  
  473. As markup and text is recognized, handlers are invoked.  The following
  474. method is used to set up handlers for different events:
  475.  
  476. =over
  477.  
  478. =item $p->handler( event => \&subroutine, $argspec )
  479.  
  480. =item $p->handler( event => $method_name, $argspec )
  481.  
  482. =item $p->handler( event => \@accum, $argspec )
  483.  
  484. =item $p->handler( event => "" );
  485.  
  486. =item $p->handler( event => undef );
  487.  
  488. =item $p->handler( event );
  489.  
  490. This method assigns a subroutine, method, or array to handle an event.
  491.  
  492. Event is one of C<text>, C<start>, C<end>, C<declaration>, C<comment>,
  493. C<process>, C<start_document>, C<end_document> or C<default>.
  494.  
  495. The C<\&subroutine> is a reference to a subroutine which is called to handle
  496. the event.
  497.  
  498. The C<$method_name> is the name of a method of $p which is called to handle
  499. the event.
  500.  
  501. The C<@accum> is an array that will hold the event information as
  502. sub-arrays.
  503.  
  504. If the second argument is "", the event is ignored.
  505. If it is undef, the default handler is invoked for the event.
  506.  
  507. The C<$argspec> is a string that describes the information to be reported
  508. for the event.  Any requested information that does not apply to a
  509. specific event is passed as C<undef>.  If argspec is omitted, then it
  510. is left unchanged.
  511.  
  512. The return value from $p->handler is the old callback routine or a
  513. reference to the accumulator array.
  514.  
  515. Any return values from handler callback routines/methods are always
  516. ignored.  A handler callback can request parsing to be aborted by
  517. invoking the $p->eof method.  A handler callback is not allowed to
  518. invoke the $p->parse() or $p->parse_file() method.  An exception will
  519. be raised if it tries.
  520.  
  521. Examples:
  522.  
  523.     $p->handler(start =>  "start", 'self, attr, attrseq, text' );
  524.  
  525. This causes the "start" method of object $p to be called for 'start' events.
  526. The callback signature is $p->start(\%attr, \@attr_seq, $text).
  527.  
  528.     $p->handler(start =>  \&start, 'attr, attrseq, text' );
  529.  
  530. This causes subroutine start() to be called for 'start' events.
  531. The callback signature is start(\%attr, \@attr_seq, $text).
  532.  
  533.     $p->handler(start =>  \@accum, '"S", attr, attrseq, text' );
  534.  
  535. This causes 'start' event information to be saved in @accum.
  536. The array elements will be ['S', \%attr, \@attr_seq, $text].
  537.  
  538.    $p->handler(start => "");
  539.  
  540. This causes 'start' events to be ignored.  It also suppresses
  541. invocations of any default handler for start events.  It is in most
  542. cases equivalent to $p->handler(start => sub {}), but is more
  543. efficient.  It is different from the empty-sub-handler in that
  544. C<skipped_text> is not reset by it.
  545.  
  546.    $p->handler(start => undef);
  547.  
  548. This causes no handler to be associated with start events.
  549. If there is a default handler it will be invoked.
  550.  
  551. =back
  552.  
  553. Filters based on tags can be set up to limit the number of events
  554. reported.  The main bottleneck during parsing is often the huge number
  555. of callbacks made from the parser.  Applying filters can improve
  556. performance significantly.
  557.  
  558. The following methods control filters:
  559.  
  560. =over
  561.  
  562. =item $p->ignore_tags( @tags )
  563.  
  564. Any C<start> and C<end> events involving any of the tags given are
  565. suppressed.
  566.  
  567. =item $p->report_tags( @tags )
  568.  
  569. Any C<start> and C<end> events involving any of the tags I<not> given
  570. are suppressed.
  571.  
  572. =item $p->ignore_elements( @tags )
  573.  
  574. Both the C<start> event and the C<end> event as well as any events that
  575. would be reported in between are suppressed.  The ignored elements can
  576. contain nested occurrences of itself.  Example:
  577.  
  578.    $p->ignore_elements(qw(script style));
  579.  
  580. The C<script> and C<style> tags will always nest properly since their
  581. content is parsed in CDATA mode.  For most other tags
  582. C<ignore_elements> must be used with caution since HTML is often not
  583. I<well formed>.
  584.  
  585. =back
  586.  
  587. =head2 Argspec
  588.  
  589. Argspec is a string containing a comma-separated list that describes
  590. the information reported by the event.  The following argspec
  591. identifier names can be used:
  592.  
  593. =over
  594.  
  595. =item C<self>
  596.  
  597. Self causes the current object to be passed to the handler.  If the
  598. handler is a method, this must be the first element in the argspec.
  599.  
  600. An alternative to passing self as an argspec is to register closures
  601. that capture $self by themselves as handlers.  Unfortunately this
  602. creates circular references which prevent the HTML::Parser object
  603. from being garbage collected.  Using the C<self> argspec avoids this
  604. problem.
  605.  
  606. =item C<tokens>
  607.  
  608. Tokens causes a reference to an array of token strings to be passed.
  609. The strings are exactly as they were found in the original text,
  610. no decoding or case changes are applied.
  611.  
  612. For C<declaration> events, the array contains each word, comment, and
  613. delimited string starting with the declaration type.
  614.  
  615. For C<comment> events, this contains each sub-comment.  If
  616. $p->strict_comments is disabled, there will be only one sub-comment.
  617.  
  618. For C<start> events, this contains the original tag name followed by
  619. the attribute name/value pairs.  The values of boolean attributes will
  620. be either the value set by $p->boolean_attribute_value, or the
  621. attribute name if no value has been set by
  622. $p->boolean_attribute_value.
  623.  
  624. For C<end> events, this contains the original tag name (always one token).
  625.  
  626. For C<process> events, this contains the process instructions (always one
  627. token).
  628.  
  629. This passes C<undef> for C<text> events.
  630.  
  631. =item C<tokenpos>
  632.  
  633. Tokenpos causes a reference to an array of token positions to be
  634. passed.  For each string that appears in C<tokens>, this array
  635. contains two numbers.  The first number is the offset of the start of
  636. the token in the original C<text> and the second number is the length
  637. of the token.
  638.  
  639. Boolean attributes in a C<start> event will have (0,0) for the
  640. attribute value offset and length.
  641.  
  642. This passes undef if there are no tokens in the event (e.g., C<text>)
  643. and for artificial C<end> events triggered by empty element tags.
  644.  
  645. If you are using these offsets and lengths to modify C<text>, you
  646. should either work from right to left, or be very careful to calculate
  647. the changes to the offsets.
  648.  
  649. =item C<token0>
  650.  
  651. Token0 causes the original text of the first token string to be
  652. passed.  This should always be the same as $tokens->[0].
  653.  
  654. For C<declaration> events, this is the declaration type.
  655.  
  656. For C<start> and C<end> events, this is the tag name.
  657.  
  658. For C<process> and non-strict C<comment> events, this is everything
  659. inside the tag.
  660.  
  661. This passes undef if there are no tokens in the event.
  662.  
  663. =item C<tagname>
  664.  
  665. This is the element name (or I<generic identifier> in SGML jargon) for
  666. start and end tags.  Since HTML is case insensitive, this name is
  667. forced to lower case to ease string matching.
  668.  
  669. Since XML is case sensitive, the tagname case is not changed when
  670. C<xml_mode> is enabled.  The same happens if the C<case_sensitive> attribute
  671. is set.
  672.  
  673. The declaration type of declaration elements is also passed as a tagname,
  674. even if that is a bit strange.
  675. In fact, in the current implementation tagname is
  676. identical to C<token0> except that the name may be forced to lower case.
  677.  
  678. =item C<tag>
  679.  
  680. Same as C<tagname>, but prefixed with "/" if it belongs to an C<end>
  681. event and "!" for a declaration.  The C<tag> does not have any prefix
  682. for C<start> events, and is in this case identical to C<tagname>.
  683.  
  684. =item C<attr>
  685.  
  686. Attr causes a reference to a hash of attribute name/value pairs to be
  687. passed.
  688.  
  689. Boolean attributes' values are either the value set by
  690. $p->boolean_attribute_value, or the attribute name if no value has been
  691. set by $p->boolean_attribute_value.
  692.  
  693. This passes undef except for C<start> events.
  694.  
  695. Unless C<xml_mode> or C<case_sensitive> is enabled, the attribute
  696. names are forced to lower case.
  697.  
  698. General entities are decoded in the attribute values and
  699. one layer of matching quotes enclosing the attribute values is removed.
  700.  
  701. =item C<attrseq>
  702.  
  703. Attrseq causes a reference to an array of attribute names to be
  704. passed.  This can be useful if you want to walk the C<attr> hash in
  705. the original sequence.
  706.  
  707. This passes undef except for C<start> events.
  708.  
  709. Unless C<xml_mode> or C<case_sensitive> is enabled, the attribute
  710. names are forced to lower case.
  711.  
  712. =item C<@attr>
  713.  
  714. Basically the same as C<attr>, but keys and values are passed as
  715. individual arguments and the original sequence of the attributes is
  716. kept.  The parameters passed will be the same as the @attr calculated
  717. here:
  718.  
  719.    @attr = map { $_ => $attr->{$_} } @$attrseq;
  720.  
  721. assuming $attr and $attrseq here are the hash and array passed as the
  722. result of C<attr> and C<attrseq> argspecs.
  723.  
  724. This passes no values for events besides C<start>.
  725.  
  726. =item C<text>
  727.  
  728. Text causes the source text (including markup element delimiters) to be
  729. passed.
  730.  
  731. =item C<dtext>
  732.  
  733. Dtext causes the decoded text to be passed.  General entities are
  734. automatically decoded unless the event was inside a CDATA section or
  735. was between literal start and end tags (C<script>, C<style>, C<textarea>,
  736. C<xmp>, and C<plaintext>).
  737.  
  738. The Unicode character set is assumed for entity decoding.  With Perl
  739. version < 5.8 only the Latin1 range is supported, and entities for
  740. characters outside the range 0..255 are left unchanged.
  741.  
  742. This passes undef except for C<text> events.
  743.  
  744. =item C<is_cdata>
  745.  
  746. Is_cdata causes a TRUE value to be passed if the event is inside a CDATA
  747. section or between literal start and end tags (C<script>,
  748. C<style>, C<textarea>, C<xmp>, and C<plaintext>).
  749.  
  750. if the flag is FALSE for a text event, then you should normally
  751. either use C<dtext> or decode the entities yourself before the text is
  752. processed further.
  753.  
  754. =item C<skipped_text>
  755.  
  756. Skipped_text returns the concatenated text of all the events that have
  757. been skipped since the last time an event was reported.  Events might
  758. be skipped because no handler is registered for them or because some
  759. filter applies.  Skipped text also includes marked section markup,
  760. since there are no events that can catch it.
  761.  
  762. If an C<"">-handler is registered for an event, then the text for this
  763. event is not included in C<skipped_text>.  Skipped text both before
  764. and after the C<"">-event is included in the next reported
  765. C<skipped_text>.
  766.  
  767. =item C<offset>
  768.  
  769. Offset causes the byte position in the HTML document of the start of
  770. the event to be passed.  The first byte in the document has offset 0.
  771.  
  772. =item C<length>
  773.  
  774. Length causes the number of bytes of the source text of the event to
  775. be passed.
  776.  
  777. =item C<offset_end>
  778.  
  779. Offset_end causes the byte position in the HTML document of the end of
  780. the event to be passed.  This is the same as C<offset> + C<length>.
  781.  
  782. =item C<event>
  783.  
  784. Event causes the event name to be passed.
  785.  
  786. The event name is one of C<text>, C<start>, C<end>, C<declaration>,
  787. C<comment>, C<process>, C<start_document> or C<end_document>.
  788.  
  789. =item C<line>
  790.  
  791. Line causes the line number of the start of the event to be passed.
  792. The first line in the document is 1.  Line counting doesn't start
  793. until at least one handler requests this value to be reported.
  794.  
  795. =item C<column>
  796.  
  797. Column causes the column number of the start of the event to be passed.
  798. The first column on a line is 0.
  799.  
  800. =item C<'...'>
  801.  
  802. A literal string of 0 to 255 characters enclosed
  803. in single (') or double (") quotes is passed as entered.
  804.  
  805. =item C<undef>
  806.  
  807. Pass an undefined value.  Useful as padding where the same handler
  808. routine is registered for multiple events.
  809.  
  810. =back
  811.  
  812. The whole argspec string can be wrapped up in C<'@{...}'> to signal
  813. that the resulting event array should be flattened.  This only makes a
  814. difference if an array reference is used as the handler target.
  815. Consider this example:
  816.  
  817.    $p->handler(text => [], 'text');
  818.    $p->handler(text => [], '@{text}']);
  819.  
  820. With two text events; C<"foo">, C<"bar">; then the first example will end
  821. up with [["foo"], ["bar"]] and the second with ["foo", "bar"] in
  822. the handler target array.
  823.  
  824.  
  825. =head2 Events
  826.  
  827. Handlers for the following events can be registered:
  828.  
  829. =over
  830.  
  831. =item C<text>
  832.  
  833. This event is triggered when plain text (characters) is recognized.
  834. The text may contain multiple lines.  A sequence of text may be broken
  835. between several text events unless $p->unbroken_text is enabled.
  836.  
  837. The parser will make sure that it does not break a word or a sequence
  838. of whitespace between two text events.
  839.  
  840. =item C<start>
  841.  
  842. This event is triggered when a start tag is recognized.
  843.  
  844. Example:
  845.  
  846.   <A HREF="http://www.perl.com/">
  847.  
  848. =item C<end>
  849.  
  850. This event is triggered when an end tag is recognized.
  851.  
  852. Example:
  853.  
  854.   </A>
  855.  
  856. =item C<declaration>
  857.  
  858. This event is triggered when a I<markup declaration> is recognized.
  859.  
  860. For typical HTML documents, the only declaration you are
  861. likely to find is <!DOCTYPE ...>.
  862.  
  863. Example:
  864.  
  865.   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  866.   "http://www.w3.org/TR/html40/strict.dtd">
  867.  
  868. DTDs inside <!DOCTYPE ...> will confuse HTML::Parser.
  869.  
  870. =item C<comment>
  871.  
  872. This event is triggered when a markup comment is recognized.
  873.  
  874. Example:
  875.  
  876.   <!-- This is a comment -- -- So is this -->
  877.  
  878. =item C<process>
  879.  
  880. This event is triggered when a processing instructions markup is
  881. recognized.
  882.  
  883. The format and content of processing instructions are system and
  884. application dependent.
  885.  
  886. Examples:
  887.  
  888.   <? HTML processing instructions >
  889.   <? XML processing instructions ?>
  890.  
  891. =item C<start_document>
  892.  
  893. This event is triggered before any other events for a new document.  A
  894. handler for it can be used to initialize stuff.  There is no document
  895. text associated with this event.
  896.  
  897. =item C<end_document>
  898.  
  899. This event is triggered when $p->eof is called and after any remaining
  900. text is flushed.  There is no document text associated with this event.
  901.  
  902. =item C<default>
  903.  
  904. This event is triggered for events that do not have a specific
  905. handler.  You can set up a handler for this event to catch stuff you
  906. did not want to catch explicitly.
  907.  
  908. =back
  909.  
  910. =head1 VERSION 2 COMPATIBILITY
  911.  
  912. When an C<HTML::Parser> object is constructed with no arguments, a set
  913. of handlers is automatically provided that is compatible with the old
  914. HTML::Parser version 2 callback methods.
  915.  
  916. This is equivalent to the following method calls:
  917.  
  918.    $p->handler(start   => "start",   "self, tagname, attr, attrseq, text");
  919.    $p->handler(end     => "end",     "self, tagname, text");
  920.    $p->handler(text    => "text",    "self, text, is_cdata");
  921.    $p->handler(process => "process", "self, token0, text");
  922.    $p->handler(comment =>
  923.              sub {
  924.          my($self, $tokens) = @_;
  925.          for (@$tokens) {$self->comment($_);}},
  926.              "self, tokens");
  927.    $p->handler(declaration =>
  928.              sub {
  929.          my $self = shift;
  930.          $self->declaration(substr($_[0], 2, -1));},
  931.              "self, text");
  932.  
  933. Setting up these handlers can also be requested with the "api_version =>
  934. 2" constructor option.
  935.  
  936. =head1 SUBCLASSING
  937.  
  938. The C<HTML::Parser> class is subclassable.  Parser objects are plain
  939. hashes and C<HTML::Parser> reserves only hash keys that start with
  940. "_hparser".  The parser state can be set up by invoking the init()
  941. method, which takes the same arguments as new().
  942.  
  943. =head1 EXAMPLES
  944.  
  945. The first simple example shows how you might strip out comments from
  946. an HTML document.  We achieve this by setting up a comment handler that
  947. does nothing and a default handler that will print out anything else:
  948.  
  949.   use HTML::Parser;
  950.   HTML::Parser->new(default_h => [sub { print shift }, 'text'],
  951.                     comment_h => [""],
  952.                    )->parse_file(shift || die) || die $!;
  953.  
  954. An alternative implementation is:
  955.  
  956.   use HTML::Parser;
  957.   HTML::Parser->new(end_document_h => [sub { print shift },
  958.                                        'skipped_text'],
  959.                     comment_h      => [""],
  960.                    )->parse_file(shift || die) || die $!;
  961.  
  962. This will in most cases be much more efficient since only a single
  963. callback will be made.
  964.  
  965. The next example prints out the text that is inside the <title>
  966. element of an HTML document.  Here we start by setting up a start
  967. handler.  When it sees the title start tag it enables a text handler
  968. that prints any text found and an end handler that will terminate
  969. parsing as soon as the title end tag is seen:
  970.  
  971.   use HTML::Parser ();
  972.  
  973.   sub start_handler
  974.   {
  975.     return if shift ne "title";
  976.     my $self = shift;
  977.     $self->handler(text => sub { print shift }, "dtext");
  978.     $self->handler(end  => sub { shift->eof if shift eq "title"; },
  979.                    "tagname,self");
  980.   }
  981.  
  982.   my $p = HTML::Parser->new(api_version => 3);
  983.   $p->handler( start => \&start_handler, "tagname,self");
  984.   $p->parse_file(shift || die) || die $!;
  985.   print "\n";
  986.  
  987. More examples are found in the F<eg/> directory of the C<HTML-Parser>
  988. distribution: the program C<hrefsub> shows how you can edit all links
  989. found in a document; the program C<htextsub> shows how to edit the text only; the
  990. program C<hstrip> shows how you can strip out certain tags/elements
  991. and/or attributes; and the program C<htext> show how to obtain the
  992. plain text, but not any script/style content.
  993.  
  994. You can browse the F<eg/> directory online from the I<[Browse]> link on
  995. the http://search.cpan.org/~gaas/HTML-Parser/ page.
  996.  
  997. =head1 BUGS
  998.  
  999. Unicode strings are not parsed correctly.  A workaround is to encode
  1000. them as UTF-8 before passing them to the HTML::Parser.  The C<Encode>
  1001. module can do that.
  1002.  
  1003. The <style> and <script> sections do not end with the first "</", but
  1004. need the complete corresponding end tag.  MSIE avoids terminating a
  1005. <script> section if the </script> occurs inside quotes.  HTML::Parser
  1006. is not that "smart".
  1007.  
  1008. When the I<strict_comment> option is enabled, we still recognize
  1009. comments where there is something other than whitespace between even
  1010. and odd "--" markers.
  1011.  
  1012. Once $p->boolean_attribute_value has been set, there is no way to
  1013. restore the default behaviour.
  1014.  
  1015. There is currently no way to get both quote characters
  1016. into the same literal argspec.
  1017.  
  1018. Empty tags, e.g. "<>" and "</>", are not recognized.  SGML allows them
  1019. to repeat the previous start tag or close the previous start tag
  1020. respectively.
  1021.  
  1022. NET tags, e.g. "code/.../" are not recognized.  This is SGML
  1023. shorthand for "<code>...</code>".
  1024.  
  1025. Unclosed start or end tags, e.g. "<tt<b>...</b</tt>" are not
  1026. recognized.
  1027.  
  1028. =head1 DIAGNOSTICS
  1029.  
  1030. The following messages may be produced by HTML::Parser.  The notation
  1031. in this listing is the same as used in L<perldiag>:
  1032.  
  1033. =over
  1034.  
  1035. =item Not a reference to a hash
  1036.  
  1037. (F) The object blessed into or subclassed from HTML::Parser is not a
  1038. hash as required by the HTML::Parser methods.
  1039.  
  1040. =item Bad signature in parser state object at %p
  1041.  
  1042. (F) The _hparser_xs_state element does not refer to a valid state structure.
  1043. Something must have changed the internal value
  1044. stored in this hash element, or the memory has been overwritten.
  1045.  
  1046. =item _hparser_xs_state element is not a reference
  1047.  
  1048. (F) The _hparser_xs_state element has been destroyed.
  1049.  
  1050. =item Can't find '_hparser_xs_state' element in HTML::Parser hash
  1051.  
  1052. (F) The _hparser_xs_state element is missing from the parser hash.
  1053. It was either deleted, or not created when the object was created.
  1054.  
  1055. =item API version %s not supported by HTML::Parser %s
  1056.  
  1057. (F) The constructor option 'api_version' with an argument greater than
  1058. or equal to 4 is reserved for future extentions.
  1059.  
  1060. =item Bad constructor option '%s'
  1061.  
  1062. (F) An unknown constructor option key was passed to the new() or
  1063. init() methods.
  1064.  
  1065. =item Parse loop not allowed
  1066.  
  1067. (F) A handler invoked the parse() or parse_file() method.
  1068. This is not permitted.
  1069.  
  1070. =item marked sections not supported
  1071.  
  1072. (F) The $p->marked_sections() method was invoked in a HTML::Parser
  1073. module that was compiled without support for marked sections.
  1074.  
  1075. =item Unknown boolean attribute (%d)
  1076.  
  1077. (F) Something is wrong with the internal logic that set up aliases for
  1078. boolean attributes.
  1079.  
  1080. =item Only code or array references allowed as handler
  1081.  
  1082. (F) The second argument for $p->handler must be either a subroutine
  1083. reference, then name of a subroutine or method, or a reference to an
  1084. array.
  1085.  
  1086. =item No handler for %s events
  1087.  
  1088. (F) The first argument to $p->handler must be a valid event name; i.e. one
  1089. of "start", "end", "text", "process", "declaration" or "comment".
  1090.  
  1091. =item Unrecognized identifier %s in argspec
  1092.  
  1093. (F) The identifier is not a known argspec name.
  1094. Use one of the names mentioned in the argspec section above.
  1095.  
  1096. =item Literal string is longer than 255 chars in argspec
  1097.  
  1098. (F) The current implementation limits the length of literals in
  1099. an argspec to 255 characters.  Make the literal shorter.
  1100.  
  1101. =item Backslash reserved for literal string in argspec
  1102.  
  1103. (F) The backslash character "\" is not allowed in argspec literals.
  1104. It is reserved to permit quoting inside a literal in a later version.
  1105.  
  1106. =item Unterminated literal string in argspec
  1107.  
  1108. (F) The terminating quote character for a literal was not found.
  1109.  
  1110. =item Bad argspec (%s)
  1111.  
  1112. (F) Only identifier names, literals, spaces and commas
  1113. are allowed in argspecs.
  1114.  
  1115. =item Missing comma separator in argspec
  1116.  
  1117. (F) Identifiers in an argspec must be separated with ",".
  1118.  
  1119. =back
  1120.  
  1121. =head1 SEE ALSO
  1122.  
  1123. L<HTML::Entities>, L<HTML::PullParser>, L<HTML::TokeParser>, L<HTML::HeadParser>,
  1124. L<HTML::LinkExtor>, L<HTML::Form>
  1125.  
  1126. L<HTML::TreeBuilder> (part of the I<HTML-Tree> distribution)
  1127.  
  1128. http://www.w3.org/TR/REC-html40
  1129.  
  1130. More information about marked sections and processing instructions may
  1131. be found at C<http://www.sgml.u-net.com/book/sgml-8.htm>.
  1132.  
  1133. =head1 COPYRIGHT
  1134.  
  1135.  Copyright 1996-2004 Gisle Aas. All rights reserved.
  1136.  Copyright 1999-2000 Michael A. Chase.  All rights reserved.
  1137.  
  1138. This library is free software; you can redistribute it and/or
  1139. modify it under the same terms as Perl itself.
  1140.  
  1141. =cut
  1142.