{
    "mode": "perldoc",
    "parameter": "HTML::Parser",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/HTML%3A%3AParser/json",
    "generated": "2026-06-10T16:15:28Z",
    "synopsis": "use strict;\nuse warnings;\nuse HTML::Parser ();\n# Create parser object\nmy $p = HTML::Parser->new(\napiversion => 3,\nstarth => [\\&start, \"tagname, attr\"],\nendh   => [\\&end,   \"tagname\"],\nmarkedsections => 1,\n);\n# Parse document text chunk by chunk\n$p->parse($chunk1);\n$p->parse($chunk2);\n# ...\n# signal end of document\n$p->eof;\n# Parse directly from file\n$p->parsefile(\"foo.html\");\n# or\nopen(my $fh, \"<:utf8\", \"foo.html\") || die;\n$p->parsefile($fh);",
    "sections": {
        "NAME": {
            "content": "HTML::Parser - HTML parser class\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use strict;\nuse warnings;\nuse HTML::Parser ();\n\n# Create parser object\nmy $p = HTML::Parser->new(\napiversion => 3,\nstarth => [\\&start, \"tagname, attr\"],\nendh   => [\\&end,   \"tagname\"],\nmarkedsections => 1,\n);\n\n# Parse document text chunk by chunk\n$p->parse($chunk1);\n$p->parse($chunk2);\n# ...\n# signal end of document\n$p->eof;\n\n# Parse directly from file\n$p->parsefile(\"foo.html\");\n# or\nopen(my $fh, \"<:utf8\", \"foo.html\") || die;\n$p->parsefile($fh);\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "Objects of the \"HTML::Parser\" class will recognize markup and separate it from plain text (alias\ndata content) in HTML documents. As different kinds of markup and text are recognized, the\ncorresponding event handlers are invoked.\n\n\"HTML::Parser\" is not a generic SGML parser. We have tried to make it able to deal with the HTML\nthat is actually \"out there\", and it normally parses as closely as possible to the way the\npopular web browsers do it instead of strictly following one of the many HTML specifications\nfrom W3C. Where there is disagreement, there is often an option that you can enable to get the\nofficial behaviour.\n\nThe document to be parsed may be supplied in arbitrary chunks. This makes on-the-fly parsing as\ndocuments are received from the network possible.\n\nIf event driven parsing does not feel right for your application, you might want to use\n\"HTML::PullParser\". This is an \"HTML::Parser\" subclass that allows a more conventional program\nstructure.\n",
            "subsections": []
        },
        "METHODS": {
            "content": "The following method is used to construct a new \"HTML::Parser\" object:\n\n$p = HTML::Parser->new( %optionsandhandlers )\nThis class method creates a new \"HTML::Parser\" object and returns it. Key/value argument\npairs may be provided to assign event handlers or initialize parser options. The handlers\nand parser options can also be set or modified later by the method calls described below.\n\nIf a top level key is in the form \"<event>h\" (e.g., \"texth\") then it assigns a handler to\nthat event, otherwise it initializes a parser option. The event handler specification value\nmust be an array reference. Multiple handlers may also be assigned with the 'handlers =>\n[%handlers]' option. See examples below.\n\nIf new() is called without any arguments, it will create a parser that uses callback methods\ncompatible with version 2 of \"HTML::Parser\". See the section on \"version 2 compatibility\"\nbelow for details.\n\nThe special constructor option 'apiversion => 2' can be used to initialize version 2\ncallbacks while still setting other options and handlers. The 'apiversion => 3' option can\nbe used if you don't want to set any options and don't want to fall back to v2 compatible\nmode.\n\nExamples:\n\n$p = HTML::Parser->new(\napiversion => 3,\ntexth => [ sub {...}, \"dtext\" ]\n);\n\nThis creates a new parser object with a text event handler subroutine that receives the\noriginal text with general entities decoded.\n\n$p = HTML::Parser->new(\napiversion => 3,\nstarth => [ 'mystart', \"self,tokens\" ]\n);\n\nThis creates a new parser object with a start event handler method that receives the $p and\nthe tokens array.\n\n$p = HTML::Parser->new(\napiversion => 3,\nhandlers => {\ntext => [\\@array, \"event,text\"],\ncomment => [\\@array, \"event,text\"],\n}\n);\n\nThis creates a new parser object that stores the event type and the original text in @array\nfor text and comment events.\n\nThe following methods feed the HTML document to the \"HTML::Parser\" object:\n\n$p->parse( $string )\nParse $string as the next chunk of the HTML document. Handlers invoked should not attempt to\nmodify the $string in-place until $p->parse returns.\n\nIf an invoked event handler aborts parsing by calling $p->eof, then $p->parse() will return\na FALSE value. Otherwise the return value is a reference to the parser object ($p).\n\n$p->parse( $coderef )\nIf a code reference is passed as the argument to be parsed, then the chunks to be parsed are\nobtained by invoking this function repeatedly. Parsing continues until the function returns\nan empty (or undefined) result. When this happens $p->eof is automatically signaled.\n\nParsing will also abort if one of the event handlers calls $p->eof.\n\nThe effect of this is the same as:\n\nwhile (1) {\nmy $chunk = &$coderef();\nif (!defined($chunk) || !length($chunk)) {\n$p->eof;\nreturn $p;\n}\n$p->parse($chunk) || return undef;\n}\n\nBut it is more efficient as this loop runs internally in XS code.\n\n$p->parsefile( $file )\nParse text directly from a file. The $file argument can be a filename, an open file handle,\nor a reference to an open file handle.\n\nIf $file contains a filename and the file can't be opened, then the method returns an\nundefined value and $! tells why it failed. Otherwise the return value is a reference to the\nparser object.\n\nIf a file handle is passed as the $file argument, then the file will normally be read until\nEOF, but not closed.\n\nIf an invoked event handler aborts parsing by calling $p->eof, then $p->parsefile() may not\nhave read the entire file.\n\nOn systems with multi-byte line terminators, the values passed for the offset and length\nargspecs may be too low if parsefile() is called on a file handle that is not in binary\nmode.\n\nIf a filename is passed in, then parsefile() will open the file in binary mode.\n\n$p->eof\nSignals the end of the HTML document. Calling the $p->eof method outside a handler callback\nwill flush any remaining buffered text (which triggers the \"text\" event if there is any\nremaining text).\n\nCalling $p->eof inside a handler will terminate parsing at that point and cause $p->parse to\nreturn a FALSE value. This also terminates parsing by $p->parsefile().\n\nAfter $p->eof has been called, the parse() and parsefile() methods can be invoked to feed\nnew documents with the parser object.\n\nThe return value from eof() is a reference to the parser object.\n\nMost parser options are controlled by boolean attributes. Each boolean attribute is enabled by\ncalling the corresponding method with a TRUE argument and disabled with a FALSE argument. The\nattribute value is left unchanged if no argument is given. The return value from each method is\nthe old attribute value.\n\nMethods that can be used to get and/or set parser options are:\n\n$p->attrencoded\n$p->attrencoded( $bool )\nBy default, the \"attr\" and @attr argspecs will have general entities for attribute values\ndecoded. Enabling this attribute leaves entities alone.\n\n$p->backquote\n$p->backquote( $bool )\nBy default, only ' and \" are recognized as quote characters around attribute values. MSIE\nalso recognizes backquotes for some reason. Enabling this attribute provides compatibility\nwith this behaviour.\n\n$p->booleanattributevalue( $val )\nThis method sets the value reported for boolean attributes inside HTML start tags. By\ndefault, the name of the attribute is also used as its value. This affects the values\nreported for \"tokens\" and \"attr\" argspecs.\n\n$p->casesensitive\n$p->casesensitive( $bool )\nBy default, tag names and attribute names are down-cased. Enabling this attribute leaves\nthem as found in the HTML source document.\n\n$p->closingplaintext\n$p->closingplaintext( $bool )\nBy default, \"plaintext\" element can never be closed. Everything up to the end of the\ndocument is parsed in CDATA mode. This historical behaviour is what at least MSIE does.\nEnabling this attribute makes closing \" </plaintext\" > tag effective and the parsing process\nwill resume after seeing this tag. This emulates early gecko-based browsers.\n\n$p->emptyelementtags\n$p->emptyelementtags( $bool )\nBy default, empty element tags are not recognized as such and the \"/\" before \">\" is just\ntreated like a normal name character (unless \"strictnames\" is enabled). Enabling this\nattribute make \"HTML::Parser\" recognize these tags.\n\nEmpty element tags look like start tags, but end with the character sequence \"/>\" instead of\n\">\". When recognized by \"HTML::Parser\" they cause an artificial end event in addition to the\nstart event. The \"text\" for the artificial end event will be empty and the \"tokenpos\" array\nwill be undefined even though the token array will have one element containing the tag name.\n\n$p->markedsections\n$p->markedsections( $bool )\nBy default, section markings like <![CDATA[...]]> are treated like ordinary text. When this\nattribute is enabled section markings are honoured.\n\nThere are currently no events associated with the marked section markup, but the text can be\nreturned as \"skippedtext\".\n\n$p->strictcomment\n$p->strictcomment( $bool )\nBy default, comments are terminated by the first occurrence of \"-->\". This is the behaviour\nof most popular browsers (like Mozilla, Opera and MSIE), but it is not correct according to\nthe official HTML standard. Officially, you need an even number of \"--\" tokens before the\nclosing \">\" is recognized and there may not be anything but whitespace between an even and\nan odd \"--\".\n\nThe official behaviour is enabled by enabling this attribute.\n\nEnabling of 'strictcomment' also disables recognizing these forms as comments:\n\n</ comment>\n<! comment>\n\n$p->strictend\n$p->strictend( $bool )\nBy default, attributes and other junk are allowed to be present on end tags in a manner that\nemulates MSIE's behaviour.\n\nThe official behaviour is enabled with this attribute. If enabled, only whitespace is\nallowed between the tagname and the final \">\".\n\n$p->strictnames\n$p->strictnames( $bool )\nBy default, almost anything is allowed in tag and attribute names. This is the behaviour of\nmost popular browsers and allows us to parse some broken tags with invalid attribute values\nlike:\n\n<IMG SRC=newprevlstGr.gif ALT=[PREV LIST] BORDER=0>\n\nBy default, \"LIST]\" is parsed as a boolean attribute, not as part of the ALT value as was\nclearly intended. This is also what Mozilla sees.\n\nThe official behaviour is enabled by enabling this attribute. If enabled, it will cause the\ntag above to be reported as text since \"LIST]\" is not a legal attribute name.\n\n$p->unbrokentext\n$p->unbrokentext( $bool )\nBy default, blocks of text are given to the text handler as soon as possible (but the parser\ntakes care always to break text at a boundary between whitespace and non-whitespace so\nsingle words and entities can always be decoded safely). This might create breaks that make\nit hard to do transformations on the text. When this attribute is enabled, blocks of text\nare always reported in one piece. This will delay the text event until the following\n(non-text) event has been recognized by the parser.\n\nNote that the \"offset\" argspec will give you the offset of the first segment of text and\n\"length\" is the combined length of the segments. Since there might be ignored tags in\nbetween, these numbers can't be used to directly index in the original document file.\n\n$p->utf8mode\n$p->utf8mode( $bool )\nEnable this option when parsing raw undecoded UTF-8. This tells the parser that the entities\nexpanded for strings reported by \"attr\", @attr and \"dtext\" should be expanded as decoded\nUTF-8 so they end up compatible with the surrounding text.\n\nIf \"utf8mode\" is enabled then it is an error to pass strings containing characters with\ncode above 255 to the parse() method, and the parse() method will croak if you try.\n\nExample: The Unicode character \"\\x{2665}\" is \"\\xE2\\x99\\xA5\" when UTF-8 encoded. The\ncharacter can also be represented by the entity \"&hearts;\" or \"&#x2665\". If we feed the\nparser:\n\n$p->parse(\"\\xE2\\x99\\xA5&hearts;\");\n\nthen \"dtext\" will be reported as \"\\xE2\\x99\\xA5\\x{2665}\" without \"utf8mode\" enabled, but as\n\"\\xE2\\x99\\xA5\\xE2\\x99\\xA5\" when enabled. The later string is what you want.\n\nThis option is only available with perl-5.8 or better.\n\n$p->xmlmode\n$p->xmlmode( $bool )\nEnabling this attribute changes the parser to allow some XML constructs. This enables the\nbehaviour controlled by individually by the \"casesensitive\", \"emptyelementtags\",\n\"strictnames\" and \"xmlpic\" attributes and also suppresses special treatment of elements\nthat are parsed as CDATA for HTML.\n\n$p->xmlpic\n$p->xmlpic( $bool )\nBy default, *processing instructions* are terminated by \">\". When this attribute is enabled,\nprocessing instructions are terminated by \"?>\" instead.\n\nAs markup and text is recognized, handlers are invoked. The following method is used to set up\nhandlers for different events:\n\n$p->handler( event => \\&subroutine, $argspec )\n$p->handler( event => $methodname, $argspec )\n$p->handler( event => \\@accum, $argspec )\n$p->handler( event => \"\" );\n$p->handler( event => undef );\n$p->handler( event );\nThis method assigns a subroutine, method, or array to handle an event.\n\nEvent is one of \"text\", \"start\", \"end\", \"declaration\", \"comment\", \"process\",\n\"startdocument\", \"enddocument\" or \"default\".\n\nThe \"\\&subroutine\" is a reference to a subroutine which is called to handle the event.\n\nThe $methodname is the name of a method of $p which is called to handle the event.\n\nThe @accum is an array that will hold the event information as sub-arrays.\n\nIf the second argument is \"\", the event is ignored. If it is undef, the default handler is\ninvoked for the event.\n\nThe $argspec is a string that describes the information to be reported for the event. Any\nrequested information that does not apply to a specific event is passed as \"undef\". If\nargspec is omitted, then it is left unchanged.\n\nThe return value from $p->handler is the old callback routine or a reference to the\naccumulator array.\n\nAny return values from handler callback routines/methods are always ignored. A handler\ncallback can request parsing to be aborted by invoking the $p->eof method. A handler\ncallback is not allowed to invoke the $p->parse() or $p->parsefile() method. An exception\nwill be raised if it tries.\n\nExamples:\n\n$p->handler(start =>  \"start\", 'self, attr, attrseq, text' );\n\nThis causes the \"start\" method of object $p to be called for 'start' events. The callback\nsignature is \"$p->start(\\%attr, \\@attrseq, $text)\".\n\n$p->handler(start =>  \\&start, 'attr, attrseq, text' );\n\nThis causes subroutine start() to be called for 'start' events. The callback signature is\nstart(\\%attr, \\@attrseq, $text).\n\n$p->handler(start =>  \\@accum, '\"S\", attr, attrseq, text' );\n\nThis causes 'start' event information to be saved in @accum. The array elements will be\n['S', \\%attr, \\@attrseq, $text].\n\n$p->handler(start => \"\");\n\nThis causes 'start' events to be ignored. It also suppresses invocations of any default\nhandler for start events. It is in most cases equivalent to $p->handler(start => sub {}),\nbut is more efficient. It is different from the empty-sub-handler in that \"skippedtext\" is\nnot reset by it.\n\n$p->handler(start => undef);\n\nThis causes no handler to be associated with start events. If there is a default handler it\nwill be invoked.\n\nFilters based on tags can be set up to limit the number of events reported. The main bottleneck\nduring parsing is often the huge number of callbacks made from the parser. Applying filters can\nimprove performance significantly.\n\nThe following methods control filters:\n\n$p->ignoreelements( @tags )\nBoth the \"start\" event and the \"end\" event as well as any events that would be reported in\nbetween are suppressed. The ignored elements can contain nested occurrences of itself.\nExample:\n\n$p->ignoreelements(qw(script style));\n\nThe \"script\" and \"style\" tags will always nest properly since their content is parsed in\nCDATA mode. For most other tags \"ignoreelements\" must be used with caution since HTML is\noften not *well formed*.\n\n$p->ignoretags( @tags )\nAny \"start\" and \"end\" events involving any of the tags given are suppressed. To reset the\nfilter (i.e. don't suppress any \"start\" and \"end\" events), call \"ignoretags\" without an\nargument.\n\n$p->reporttags( @tags )\nAny \"start\" and \"end\" events involving any of the tags *not* given are suppressed. To reset\nthe filter (i.e. report all \"start\" and \"end\" events), call \"reporttags\" without an\nargument.\n\nInternally, the system has two filter lists, one for \"reporttags\" and one for \"ignoretags\",\nand both filters are applied. This effectively gives \"ignoretags\" precedence over\n\"reporttags\".\n\nExamples:\n\n$p->ignoretags(qw(style));\n$p->reporttags(qw(script style));\n\nresults in only \"script\" events being reported.\n",
            "subsections": [
                {
                    "name": "Argspec",
                    "content": "Argspec is a string containing a comma-separated list that describes the information reported by\nthe event. The following argspec identifier names can be used:\n\n\"attr\"\nAttr causes a reference to a hash of attribute name/value pairs to be passed.\n\nBoolean attributes' values are either the value set by $p->booleanattributevalue, or the\nattribute name if no value has been set by $p->booleanattributevalue.\n\nThis passes undef except for \"start\" events.\n\nUnless \"xmlmode\" or \"casesensitive\" is enabled, the attribute names are forced to lower\ncase.\n\nGeneral entities are decoded in the attribute values and one layer of matching quotes\nenclosing the attribute values is removed.\n\nThe Unicode character set is assumed for entity decoding.\n\n@attr\nBasically the same as \"attr\", but keys and values are passed as individual arguments and the\noriginal sequence of the attributes is kept. The parameters passed will be the same as the\n@attr calculated here:\n\n@attr = map { $ => $attr->{$} } @$attrseq;\n\nassuming $attr and $attrseq here are the hash and array passed as the result of \"attr\" and\n\"attrseq\" argspecs.\n\nThis passes no values for events besides \"start\".\n\n\"attrseq\"\nAttrseq causes a reference to an array of attribute names to be passed. This can be useful\nif you want to walk the \"attr\" hash in the original sequence.\n\nThis passes undef except for \"start\" events.\n\nUnless \"xmlmode\" or \"casesensitive\" is enabled, the attribute names are forced to lower\ncase.\n\n\"column\"\nColumn causes the column number of the start of the event to be passed. The first column on\na line is 0.\n\n\"dtext\"\nDtext causes the decoded text to be passed. General entities are automatically decoded\nunless the event was inside a CDATA section or was between literal start and end tags\n(\"script\", \"style\", \"xmp\", \"iframe\", \"title\", \"textarea\" and \"plaintext\").\n\nThe Unicode character set is assumed for entity decoding. With Perl version 5.6 or earlier\nonly the Latin-1 range is supported, and entities for characters outside the range 0..255\nare left unchanged.\n\nThis passes undef except for \"text\" events.\n\n\"event\"\nEvent causes the event name to be passed.\n\nThe event name is one of \"text\", \"start\", \"end\", \"declaration\", \"comment\", \"process\",\n\"startdocument\" or \"enddocument\".\n\n\"iscdata\"\nIscdata causes a TRUE value to be passed if the event is inside a CDATA section or between\nliteral start and end tags (\"script\", \"style\", \"xmp\", \"iframe\", \"title\", \"textarea\" and\n\"plaintext\").\n\nif the flag is FALSE for a text event, then you should normally either use \"dtext\" or decode\nthe entities yourself before the text is processed further.\n\n\"length\"\nLength causes the number of bytes of the source text of the event to be passed.\n\n\"line\"\nLine causes the line number of the start of the event to be passed. The first line in the\ndocument is 1. Line counting doesn't start until at least one handler requests this value to\nbe reported.\n\n\"offset\"\nOffset causes the byte position in the HTML document of the start of the event to be passed.\nThe first byte in the document has offset 0.\n\n\"offsetend\"\nOffsetend causes the byte position in the HTML document of the end of the event to be\npassed. This is the same as \"offset\" + \"length\".\n\n\"self\"\nSelf causes the current object to be passed to the handler. If the handler is a method, this\nmust be the first element in the argspec.\n\nAn alternative to passing self as an argspec is to register closures that capture $self by\nthemselves as handlers. Unfortunately this creates circular references which prevent the\nHTML::Parser object from being garbage collected. Using the \"self\" argspec avoids this\nproblem.\n\n\"skippedtext\"\nSkippedtext returns the concatenated text of all the events that have been skipped since\nthe last time an event was reported. Events might be skipped because no handler is\nregistered for them or because some filter applies. Skipped text also includes marked\nsection markup, since there are no events that can catch it.\n\nIf an \"\"-handler is registered for an event, then the text for this event is not included in\n\"skippedtext\". Skipped text both before and after the \"\"-event is included in the next\nreported \"skippedtext\".\n\n\"tag\"\nSame as \"tagname\", but prefixed with \"/\" if it belongs to an \"end\" event and \"!\" for a\ndeclaration. The \"tag\" does not have any prefix for \"start\" events, and is in this case\nidentical to \"tagname\".\n\n\"tagname\"\nThis is the element name (or *generic identifier* in SGML jargon) for start and end tags.\nSince HTML is case insensitive, this name is forced to lower case to ease string matching.\n\nSince XML is case sensitive, the tagname case is not changed when \"xmlmode\" is enabled. The\nsame happens if the \"casesensitive\" attribute is set.\n\nThe declaration type of declaration elements is also passed as a tagname, even if that is a\nbit strange. In fact, in the current implementation tagname is identical to \"token0\" except\nthat the name may be forced to lower case.\n\n\"token0\"\nToken0 causes the original text of the first token string to be passed. This should always\nbe the same as $tokens->[0].\n\nFor \"declaration\" events, this is the declaration type.\n\nFor \"start\" and \"end\" events, this is the tag name.\n\nFor \"process\" and non-strict \"comment\" events, this is everything inside the tag.\n\nThis passes undef if there are no tokens in the event.\n\n\"tokenpos\"\nTokenpos causes a reference to an array of token positions to be passed. For each string\nthat appears in \"tokens\", this array contains two numbers. The first number is the offset of\nthe start of the token in the original \"text\" and the second number is the length of the\ntoken.\n\nBoolean attributes in a \"start\" event will have (0,0) for the attribute value offset and\nlength.\n\nThis passes undef if there are no tokens in the event (e.g., \"text\") and for artificial\n\"end\" events triggered by empty element tags.\n\nIf you are using these offsets and lengths to modify \"text\", you should either work from\nright to left, or be very careful to calculate the changes to the offsets.\n\n\"tokens\"\nTokens causes a reference to an array of token strings to be passed. The strings are exactly\nas they were found in the original text, no decoding or case changes are applied.\n\nFor \"declaration\" events, the array contains each word, comment, and delimited string\nstarting with the declaration type.\n\nFor \"comment\" events, this contains each sub-comment. If $p->strictcomments is disabled,\nthere will be only one sub-comment.\n\nFor \"start\" events, this contains the original tag name followed by the attribute name/value\npairs. The values of boolean attributes will be either the value set by\n$p->booleanattributevalue, or the attribute name if no value has been set by\n$p->booleanattributevalue.\n\nFor \"end\" events, this contains the original tag name (always one token).\n\nFor \"process\" events, this contains the process instructions (always one token).\n\nThis passes \"undef\" for \"text\" events.\n\n\"text\"\nText causes the source text (including markup element delimiters) to be passed.\n\n\"undef\"\nPass an undefined value. Useful as padding where the same handler routine is registered for\nmultiple events.\n\n'...'\nA literal string of 0 to 255 characters enclosed in single (') or double (\") quotes is\npassed as entered.\n\nThe whole argspec string can be wrapped up in '@{...}' to signal that the resulting event array\nshould be flattened. This only makes a difference if an array reference is used as the handler\ntarget. Consider this example:\n\n$p->handler(text => [], 'text');\n$p->handler(text => [], '@{text}']);\n\nWith two text events; \"foo\", \"bar\"; then the first example will end up with [[\"foo\"], [\"bar\"]]\nand the second with [\"foo\", \"bar\"] in the handler target array.\n"
                },
                {
                    "name": "Events",
                    "content": "Handlers for the following events can be registered:\n\n\"comment\"\nThis event is triggered when a markup comment is recognized.\n\nExample:\n\n<!-- This is a comment -- -- So is this -->\n\n\"declaration\"\nThis event is triggered when a *markup declaration* is recognized.\n\nFor typical HTML documents, the only declaration you are likely to find is <!DOCTYPE ...>.\n\nExample:\n\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n\"http://www.w3.org/TR/html4/strict.dtd\">\n\nDTDs inside <!DOCTYPE ...> will confuse HTML::Parser.\n\n\"default\"\nThis event is triggered for events that do not have a specific handler. You can set up a\nhandler for this event to catch stuff you did not want to catch explicitly.\n\n\"end\"\nThis event is triggered when an end tag is recognized.\n\nExample:\n\n</A>\n\n\"enddocument\"\nThis event is triggered when $p->eof is called and after any remaining text is flushed.\nThere is no document text associated with this event.\n\n\"process\"\nThis event is triggered when a processing instructions markup is recognized.\n\nThe format and content of processing instructions are system and application dependent.\n\nExamples:\n\n<? HTML processing instructions >\n<? XML processing instructions ?>\n\n\"start\"\nThis event is triggered when a start tag is recognized.\n\nExample:\n\n<A HREF=\"http://www.perl.com/\">\n\n\"startdocument\"\nThis event is triggered before any other events for a new document. A handler for it can be\nused to initialize stuff. There is no document text associated with this event.\n\n\"text\"\nThis event is triggered when plain text (characters) is recognized. The text may contain\nmultiple lines. A sequence of text may be broken between several text events unless\n$p->unbrokentext is enabled.\n\nThe parser will make sure that it does not break a word or a sequence of whitespace between\ntwo text events.\n"
                },
                {
                    "name": "Unicode",
                    "content": "\"HTML::Parser\" can parse Unicode strings when running under perl-5.8 or better. If Unicode is\npassed to $p->parse() then chunks of Unicode will be reported to the handlers. The offset and\nlength argspecs will also report their position in terms of characters.\n\nIt is safe to parse raw undecoded UTF-8 if you either avoid decoding entities and make sure to\nnot use *argspecs* that do, or enable the \"utf8mode\" for the parser. Parsing of undecoded UTF-8\nmight be useful when parsing from a file where you need the reported offsets and lengths to\nmatch the byte offsets in the file.\n\nIf a filename is passed to $p->parsefile() then the file will be read in binary mode. This will\nbe fine if the file contains only ASCII or Latin-1 characters. If the file contains UTF-8\nencoded text then care must be taken when decoding entities as described in the previous\nparagraph, but better is to open the file with the UTF-8 layer so that it is decoded properly:\n\nopen(my $fh, \"<:utf8\", \"index.html\") || die \"...: $!\";\n$p->parsefile($fh);\n\nIf the file contains text encoded in a charset besides ASCII, Latin-1 or UTF-8 then decoding\nwill always be needed.\n"
                }
            ]
        },
        "VERSION 2 COMPATIBILITY": {
            "content": "When an \"HTML::Parser\" object is constructed with no arguments, a set of handlers is\nautomatically provided that is compatible with the old HTML::Parser version 2 callback methods.\n\nThis is equivalent to the following method calls:\n\n$p->handler(start   => \"start\",   \"self, tagname, attr, attrseq, text\");\n$p->handler(end     => \"end\",     \"self, tagname, text\");\n$p->handler(text    => \"text\",    \"self, text, iscdata\");\n$p->handler(process => \"process\", \"self, token0, text\");\n$p->handler(\ncomment => sub {\nmy($self, $tokens) = @;\nfor (@$tokens) {$self->comment($);}\n},\n\"self, tokens\"\n);\n$p->handler(\ndeclaration => sub {\nmy $self = shift;\n$self->declaration(substr($[0], 2, -1));\n},\n\"self, text\"\n);\n\nSetting up these handlers can also be requested with the \"apiversion => 2\" constructor option.\n",
            "subsections": []
        },
        "SUBCLASSING": {
            "content": "The \"HTML::Parser\" class is able to be subclassed. Parser objects are plain hashes and\n\"HTML::Parser\" reserves only hash keys that start with \"hparser\". The parser state can be set\nup by invoking the init() method, which takes the same arguments as new().\n",
            "subsections": []
        },
        "EXAMPLES": {
            "content": "The first simple example shows how you might strip out comments from an HTML document. We\nachieve this by setting up a comment handler that does nothing and a default handler that will\nprint out anything else:\n\nuse HTML::Parser;\nHTML::Parser->new(\ndefaulth => [sub { print shift }, 'text'],\ncommenth => [\"\"],\n)->parsefile(shift || die) || die $!;\n\nAn alternative implementation is:\n\nuse HTML::Parser;\nHTML::Parser->new(\nenddocumenth => [sub { print shift }, 'skippedtext'],\ncommenth      => [\"\"],\n)->parsefile(shift || die) || die $!;\n\nThis will in most cases be much more efficient since only a single callback will be made.\n\nThe next example prints out the text that is inside the <title> element of an HTML document.\nHere we start by setting up a start handler. When it sees the title start tag it enables a text\nhandler that prints any text found and an end handler that will terminate parsing as soon as the\ntitle end tag is seen:\n\nuse HTML::Parser ();\n\nsub starthandler {\nreturn if shift ne \"title\";\nmy $self = shift;\n$self->handler(text => sub { print shift }, \"dtext\");\n$self->handler(\nend  => sub {\nshift->eof if shift eq \"title\";\n},\n\"tagname,self\"\n);\n}\n\nmy $p = HTML::Parser->new(apiversion => 3);\n$p->handler(start => \\&starthandler, \"tagname,self\");\n$p->parsefile(shift || die) || die $!;\nprint \"\\n\";\n\nOn a Debian box, more examples can be found in the /usr/share/doc/libhtml-parser-perl/examples\ndirectory. The program \"hrefsub\" shows how you can edit all links found in a document and\n\"htextsub\" how to edit the text only; the program \"hstrip\" shows how you can strip out certain\ntags/elements and/or attributes; and the program \"htext\" show how to obtain the plain text, but\nnot any script/style content.\n\nYou can browse the eg/ directory online from the *[Browse]* link on the\nhttp://search.cpan.org/~gaas/HTML-Parser/ page.\n",
            "subsections": []
        },
        "BUGS": {
            "content": "The <style> and <script> sections do not end with the first \"</\", but need the complete\ncorresponding end tag. The standard behaviour is not really practical.\n\nWhen the *strictcomment* option is enabled, we still recognize comments where there is\nsomething other than whitespace between even and odd \"--\" markers.\n\nOnce $p->booleanattributevalue has been set, there is no way to restore the default behaviour.\n\nThere is currently no way to get both quote characters into the same literal argspec.\n\nEmpty tags, e.g. \"<>\" and \"</>\", are not recognized. SGML allows them to repeat the previous\nstart tag or close the previous start tag respectively.\n\nNET tags, e.g. \"code/.../\" are not recognized. This is SGML shorthand for \"<code>...</code>\".\n\nIncomplete start or end tags, e.g. \"<tt<b>...</b</tt>\" are not recognized.\n",
            "subsections": []
        },
        "DIAGNOSTICS": {
            "content": "The following messages may be produced by HTML::Parser. The notation in this listing is the same\nas used in perldiag:\n\nNot a reference to a hash\n(F) The object blessed into or subclassed from HTML::Parser is not a hash as required by the\nHTML::Parser methods.\n\nBad signature in parser state object at %p\n(F) The hparserxsstate element does not refer to a valid state structure. Something must\nhave changed the internal value stored in this hash element, or the memory has been\noverwritten.\n\nhparserxsstate element is not a reference\n(F) The hparserxsstate element has been destroyed.\n\nCan't find 'hparserxsstate' element in HTML::Parser hash\n(F) The hparserxsstate element is missing from the parser hash. It was either deleted, or\nnot created when the object was created.\n\nAPI version %s not supported by HTML::Parser %s\n(F) The constructor option 'apiversion' with an argument greater than or equal to 4 is\nreserved for future extensions.\n\nBad constructor option '%s'\n(F) An unknown constructor option key was passed to the new() or init() methods.\n\nParse loop not allowed\n(F) A handler invoked the parse() or parsefile() method. This is not permitted.\n\nmarked sections not supported\n(F) The $p->markedsections() method was invoked in a HTML::Parser module that was compiled\nwithout support for marked sections.\n\nUnknown boolean attribute (%d)\n(F) Something is wrong with the internal logic that set up aliases for boolean attributes.\n\nOnly code or array references allowed as handler\n(F) The second argument for $p->handler must be either a subroutine reference, then name of\na subroutine or method, or a reference to an array.\n\nNo handler for %s events\n(F) The first argument to $p->handler must be a valid event name; i.e. one of \"start\",\n\"end\", \"text\", \"process\", \"declaration\" or \"comment\".\n\nUnrecognized identifier %s in argspec\n(F) The identifier is not a known argspec name. Use one of the names mentioned in the\nargspec section above.\n\nLiteral string is longer than 255 chars in argspec\n(F) The current implementation limits the length of literals in an argspec to 255\ncharacters. Make the literal shorter.\n\nBackslash reserved for literal string in argspec\n(F) The backslash character \"\\\" is not allowed in argspec literals. It is reserved to permit\nquoting inside a literal in a later version.\n\nUnterminated literal string in argspec\n(F) The terminating quote character for a literal was not found.\n\nBad argspec (%s)\n(F) Only identifier names, literals, spaces and commas are allowed in argspecs.\n\nMissing comma separator in argspec\n(F) Identifiers in an argspec must be separated with \",\".\n\nParsing of undecoded UTF-8 will give garbage when decoding entities\n(W) The first chunk parsed appears to contain undecoded UTF-8 and one or more argspecs that\ndecode entities are used for the callback handlers.\n\nThe result of decoding will be a mix of encoded and decoded characters for any entities that\nexpand to characters with code above 127. This is not a good thing.\n\nThe recommended solution is to apply Encode::decodeutf8() on the data before feeding it to\nthe $p->parse(). For $p->parsefile() pass a file that has been opened in \":utf8\" mode.\n\nThe alternative solution is to enable the \"utf8mode\" and not decode before passing strings\nto $p->parse(). The parser can process raw undecoded UTF-8 sanely if the \"utf8mode\" is\nenabled, or if the \"attr\", @attr or \"dtext\" argspecs are avoided.\n\nParsing string decoded with wrong endian selection\n(W) The first character in the document is U+FFFE. This is not a legal Unicode character but\na byte swapped \"BOM\". The result of parsing will likely be garbage.\n\nParsing of undecoded UTF-32\n(W) The parser found the Unicode UTF-32 \"BOM\" signature at the start of the document. The\nresult of parsing will likely be garbage.\n\nParsing of undecoded UTF-16\n(W) The parser found the Unicode UTF-16 \"BOM\" signature at the start of the document. The\nresult of parsing will likely be garbage.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "HTML::Entities, HTML::PullParser, HTML::TokeParser, HTML::HeadParser, HTML::LinkExtor,\nHTML::Form\n\nHTML::TreeBuilder (part of the *HTML-Tree* distribution)\n\n<http://www.w3.org/TR/html4/>\n\nMore information about marked sections and processing instructions may be found at\n<http://www.is-thought.co.uk/book/sgml-8.htm>.\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "Copyright 1996-2016 Gisle Aas. All rights reserved.\nCopyright 1999-2000 Michael A. Chase.  All rights reserved.\n\nThis library is free software; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n",
            "subsections": []
        }
    },
    "summary": "HTML::Parser - HTML parser class",
    "flags": [],
    "examples": [
        "The first simple example shows how you might strip out comments from an HTML document. We",
        "achieve this by setting up a comment handler that does nothing and a default handler that will",
        "print out anything else:",
        "use HTML::Parser;",
        "HTML::Parser->new(",
        "defaulth => [sub { print shift }, 'text'],",
        "commenth => [\"\"],",
        ")->parsefile(shift || die) || die $!;",
        "An alternative implementation is:",
        "use HTML::Parser;",
        "HTML::Parser->new(",
        "enddocumenth => [sub { print shift }, 'skippedtext'],",
        "commenth      => [\"\"],",
        ")->parsefile(shift || die) || die $!;",
        "This will in most cases be much more efficient since only a single callback will be made.",
        "The next example prints out the text that is inside the <title> element of an HTML document.",
        "Here we start by setting up a start handler. When it sees the title start tag it enables a text",
        "handler that prints any text found and an end handler that will terminate parsing as soon as the",
        "title end tag is seen:",
        "use HTML::Parser ();",
        "sub starthandler {",
        "return if shift ne \"title\";",
        "my $self = shift;",
        "$self->handler(text => sub { print shift }, \"dtext\");",
        "$self->handler(",
        "end  => sub {",
        "shift->eof if shift eq \"title\";",
        "},",
        "\"tagname,self\"",
        ");",
        "my $p = HTML::Parser->new(apiversion => 3);",
        "$p->handler(start => \\&starthandler, \"tagname,self\");",
        "$p->parsefile(shift || die) || die $!;",
        "print \"\\n\";",
        "On a Debian box, more examples can be found in the /usr/share/doc/libhtml-parser-perl/examples",
        "directory. The program \"hrefsub\" shows how you can edit all links found in a document and",
        "\"htextsub\" how to edit the text only; the program \"hstrip\" shows how you can strip out certain",
        "tags/elements and/or attributes; and the program \"htext\" show how to obtain the plain text, but",
        "not any script/style content.",
        "You can browse the eg/ directory online from the *[Browse]* link on the",
        "http://search.cpan.org/~gaas/HTML-Parser/ page."
    ],
    "see_also": []
}