<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package HTML::TokeParser::Simple;

use strict;
use HTML::TokeParser;
use HTML::TokeParser::Simple::Token;
use HTML::TokeParser::Simple::Token::Tag;
use HTML::TokeParser::Simple::Token::Tag::Start;
use HTML::TokeParser::Simple::Token::Tag::End;
use HTML::TokeParser::Simple::Token::Text;
use HTML::TokeParser::Simple::Token::Comment;
use HTML::TokeParser::Simple::Token::Declaration;
use HTML::TokeParser::Simple::Token::ProcessInstruction;

use vars qw/ @ISA $VERSION $REVISION /;

$REVISION = '$Id: Simple.pm 13983 2007-03-15 01:32:44Z lh92 $';
$VERSION  = '3.15';
@ISA = qw/ HTML::TokeParser /;

# constructors

my %FACTORY_CLASSES = (
    S   =&gt; 'HTML::TokeParser::Simple::Token::Tag::Start',
    E   =&gt; 'HTML::TokeParser::Simple::Token::Tag::End',
    T   =&gt; 'HTML::TokeParser::Simple::Token::Text',
    C   =&gt; 'HTML::TokeParser::Simple::Token::Comment',
    D   =&gt; 'HTML::TokeParser::Simple::Token::Declaration',
    PI  =&gt; 'HTML::TokeParser::Simple::Token::ProcessInstruction',
);

sub _croak {
    my ($proto, $message) = @_;
    require Carp;
    Carp::croak($message);
}

sub new {
    my ($class, @args) = @_;
    return 1 == @args
        ? $class-&gt;SUPER::new(@args)
        : $class-&gt;_init(@args);
}

sub _init {
    my ($class, $source_type, $source) = @_;
    my %sources = (
        file   =&gt; sub { $source },
        handle =&gt; sub { $source },
        string =&gt; sub { \$source },
        url    =&gt; sub {
            eval "require LWP::Simple";
            $class-&gt;_croak("Cannot load LWP::Simple: $@") if $@;
            my $content = LWP::Simple::get($source);
            $class-&gt;_croak("Could not fetch content from ($source)")
                unless defined $content;
            return \$content;
        },
    );
    unless (exists $sources{$source_type}) {
        $class-&gt;_croak("Unknown source type ($source_type)");
    }
    return $class-&gt;new($sources{$source_type}-&gt;());
}

sub get_token {
    my $self = shift;
    my @args = @_;
    my $token = $self-&gt;SUPER::get_token( @args );
    return unless defined $token;
    if (my $factory_class = $FACTORY_CLASSES{$token-&gt;[0]}) {
        return $factory_class-&gt;new($token);
    }
    else {
        # this should never happen
        $self-&gt;_croak("Cannot determine token class for token (@$token)");
    }
}

sub get_tag {
    my $self = shift;
    my @args = @_;
    my $token = $self-&gt;SUPER::get_tag( @args );
    return unless defined $token;
    return $token-&gt;[0] =~ /^\//
        ?  HTML::TokeParser::Simple::Token::Tag::End-&gt;new($token)
        :  HTML::TokeParser::Simple::Token::Tag::Start-&gt;new($token);
}

sub peek {
    my ($self, $count) = @_;
    $count  ||= 1;
    
    unless ($count =~ /^\d+$/) {
        $self-&gt;_croak("Argument to peek() must be a positive integer, not ($count)");
    }

    my $items = 0;
    my $html  = '';
    my @tokens;
    while ( $items++ &lt; $count &amp;&amp; defined ( my $token = $self-&gt;get_token ) ) {
        $html .= $token-&gt;as_is;
        push @tokens, $token;
    }
    $self-&gt;unget_token(@tokens);
    return $html;
}

1;

__END__

=head1 NAME

HTML::TokeParser::Simple - Easy to use C&lt;HTML::TokeParser&gt; interface

=head1 SYNOPSIS

 use HTML::TokeParser::Simple;
 my $p = HTML::TokeParser::Simple-&gt;new( $somefile );

 while ( my $token = $p-&gt;get_token ) {
     # This prints all text in an HTML doc (i.e., it strips the HTML)
     next unless $token-&gt;is_text;
     print $token-&gt;as_is;
 }


=head1 DESCRIPTION

C&lt;HTML::TokeParser&gt; is an excellent module that's often used for parsing HTML.
However, the tokens returned are not exactly intuitive to parse:

 ["S",  $tag, $attr, $attrseq, $text]
 ["E",  $tag, $text]
 ["T",  $text, $is_data]
 ["C",  $text]
 ["D",  $text]
 ["PI", $token0, $text]

To simplify this, C&lt;HTML::TokeParser::Simple&gt; allows the user ask more
intuitive (read: more self-documenting) questions about the tokens returned.

You can also rebuild some tags on the fly.  Frequently, the attributes
associated with start tags need to be altered, added to, or deleted.  This
functionality is built in.

Since this is a subclass of C&lt;HTML::TokeParser&gt;, all C&lt;HTML::TokeParser&gt;
methods are available.  To truly appreciate the power of this module, please
read the documentation for C&lt;HTML::TokeParser&gt; and C&lt;HTML::Parser&gt;.

=head1 CONTRUCTORS

=head2 C&lt;new($source)&gt;

The constructor for C&lt;HTML::TokeParser::Simple&gt; can be used just like
C&lt;HTML::TokeParser&gt;'s constructor:

  my $parser = HTML::TokeParser::Simple-&gt;new($filename);
  # or
  my $parser = HTML::TokeParser::Simple-&gt;new($filehandle);
  # or
  my $parser = HTML::TokeParser::Simple-&gt;new(\$html_string);

=head2 C&lt;new($source_type, $source)&gt;

If you wish to be more explicit, there is a new style of
constructor avaiable.

  my $parser = HTML::TokeParser::Simple-&gt;new(file   =&gt; $filename);
  # or
  my $parser = HTML::TokeParser::Simple-&gt;new(handle =&gt; $filehandle);
  # or
  my $parser = HTML::TokeParser::Simple-&gt;new(string =&gt; $html_string);

Note that you do not have to provide a reference for the string if using the
string constructor.

As a convenience, you can also attempt to fetch the HTML directly from a URL.

  my $parser = HTML::TokeParser::Simple-&gt;new(url =&gt; 'http://some.url');

This method relies on C&lt;LWP::Simple&gt;.  If this module is not found or the page
cannot be fetched, the constructor will C&lt;croak()&gt;.

=head1 PARSER METHODS

=head2 get_token

This method will return the next token that C&lt;HTML::TokeParser::get_token()&gt;
method would return.  However, it will be blessed into a class appropriate
which represents the token type.

=head2 get_tag

This method will return the next token that C&lt;HTML::TokeParser::get_tag()&gt;
method would return.  However, it will be blessed into either the
L&lt;HTML::TokeParser::Simple::Token::Tag::Start&gt; or
L&lt;HTML::TokeParser::Simple::Token::Tag::End&gt; class.

=head2 peek

As of version C&lt;3.14&gt;, you can now C&lt;peek()&gt; at the upcomings tokens without
affecting the state of the parser.  By default, C&lt;peek()&gt; will return the text
of the next token, but specifying an integer C&lt;$count&gt; will return the text of
the next C&lt;$count&gt; tokens.

This is useful when you're trying to debug where you are in a document.

 warn $parser-&gt;peek(3); # show the next 3 tokens

=head1 ACCESSORS

The following methods may be called on the token object which is returned,
not on the parser object.

=head2 Boolean Accessors

These accessors return true or false.

=over 4

=item * C&lt;is_tag([$tag])&gt;

Use this to determine if you have any tag.  An optional "tag type" may be
passed.  This will allow you to match if it's a I&lt;particular&gt; tag.  The
supplied tag is case-insensitive.

 if ( $token-&gt;is_tag ) { ... }

Optionally, you may pass a regular expression as an argument.

=item * C&lt;is_start_tag([$tag])&gt;

Use this to determine if you have a start tag.  An optional "tag type" may be
passed.  This will allow you to match if it's a I&lt;particular&gt; start tag.  The
supplied tag is case-insensitive.

 if ( $token-&gt;is_start_tag ) { ... }
 if ( $token-&gt;is_start_tag( 'font' ) ) { ... }

Optionally, you may pass a regular expression as an argument.  To match all
header (h1, h2, ... h6) tags:

 if ( $token-&gt;is_start_tag( qr/^h[123456]$/ ) ) { ... }

=item * C&lt;is_end_tag([$tag])&gt;

Use this to determine if you have an end tag.  An optional "tag type" may be
passed.  This will allow you to match if it's a I&lt;particular&gt; end tag.  The
supplied tag is case-insensitive.

When testing for an end tag, the forward slash on the tag is optional.

 while ( $token = $p-&gt;get_token ) {
   if ( $token-&gt;is_end_tag( 'form' ) ) { ... }
 }

Or:

 while ( $token = $p-&gt;get_token ) {
   if ( $token-&gt;is_end_tag( '/form' ) ) { ... }
 }

Optionally, you may pass a regular expression as an argument.

=item * C&lt;is_text()&gt;

Use this to determine if you have text.  Note that this is I&lt;not&gt; to be
confused with the C&lt;return_text&gt; (I&lt;deprecated&gt;) method described below!
C&lt;is_text&gt; will identify text that the user typically sees display in the Web
browser.

=item * C&lt;is_comment()&gt;

Are you still reading this?  Nobody reads POD.  Don't you know you're supposed
to go to CLPM, ask a question that's answered in the POD and get flamed?  It's
a rite of passage.

Really.

C&lt;is_comment&gt; is used to identify comments.  See the HTML::Parser documentation
for more information about comments.  There's more than you might think.

=item * C&lt;is_declaration()&gt;

This will match the DTD at the top of your HTML. (You I&lt;do&gt; use DTD's, don't
you?)

=item * C&lt;is_process_instruction()&gt;

Process Instructions are from XML.  This is very handy if you need to parse out
PHP and similar things with a parser.

Currently, there appear to be some problems with process instructions.  You can
override C&lt;HTML::TokeParser::Simple::Token::ProcessInstruction&gt; if you need to.

=item * C&lt;is_pi()&gt;

This is a shorthand for C&lt;is_process_instruction()&gt;.

=back

=head2 Data Accessors

Some of these were originally C&lt;return_&gt; methods, but that name was not only
unwieldy, but also went against reasonable conventions.  The C&lt;get_&gt; methods
listed below still have C&lt;return_&gt; methods available for backwards
compatibility reasons, but they merely call their C&lt;get_&gt; counterpart.  For
example, calling C&lt;return_tag()&gt; actually calls C&lt;get_tag()&gt; internally.

=over 4

=item * C&lt;get_tag()&gt;

Do you have a start tag or end tag?  This will return the type (lower case).
Note that this is I&lt;not&gt; the same as the C&lt;get_tag()&gt; method on the actual
parser object.

=item * C&lt;get_attr([$attribute])&gt;

If you have a start tag, this will return a hash ref with the attribute names
as keys and the values as the values.

If you pass in an attribute name, it will return the value for just that
attribute.  

Returns false if the token is not a start tag.

=item * C&lt;get_attrseq()&gt;

For a start tag, this is an array reference with the sequence of the
attributes, if any.

Returns false if the token is not a start tag.

=item * C&lt;return_text()&gt;

This method has been heavily deprecated (for a couple of years) in favor of
C&lt;as_is&gt;.  Programmers were getting confused over the difference between
C&lt;is_text&gt;, C&lt;return_text&gt;, and some parser methods such as
C&lt;HTML::TokeParser::get_text&gt; and friends.

Using this method still succeeds, but will now carp and B&lt;will be removed&gt;
in the next major release of this module.

=item * C&lt;as_is()&gt;

This is the exact text of whatever the token is representing.

=item * C&lt;get_token0()&gt;

For processing instructions, this will return the token found immediately after
the opening tag.  Example:  For &lt;?php, "php" will be the start of the returned
string.

Note that process instruction handling appears to be incomplete in
C&lt;HTML::TokeParser&gt;.

Returns false if the token is not a process instruction.

=back

=head1 MUTATORS

The C&lt;delete_attr()&gt; and C&lt;set_attr()&gt; methods allow the programmer to rewrite
start tag attributes on the fly.  It should be noted that bad HTML will be
"corrected" by this.  Specifically, the new tag will have all attributes
lower-cased with the values properly quoted.

Self-closing tags (e.g. E&lt;lt&gt;hr /E&lt;gt&gt;) are also handled correctly.  Some older
browsers require a space prior to the final slash in a self-closed tag.  If
such a space is detected in the original HTML, it will be preserved.

Calling a mutator on an token type that does not support that property is a
no-op.  For example:

 if ($token-&gt;is_comment) {
    $token-&gt;set_attr(foo =&gt; 'bar'); # does nothing
 }

=over 4

=item * C&lt;delete_attr($name)&gt;

This method attempts to delete the attribute specified.  It will silently fail
if called on anything other than a start tag.  The argument is
case-insensitive, but must otherwise be an exact match of the attribute you are
attempting to delete.  If the attribute is not found, the method will return
without changing the tag.

 # &lt;body bgcolor="#FFFFFF"&gt;
 $token-&gt;delete_attr('bgcolor');
 print $token-&gt;as_is;
 # &lt;body&gt;
 
After this method is called, if successful, the C&lt;as_is()&gt;, C&lt;get_attr()&gt;
and C&lt;get_attrseq()&gt; methods will all return updated results.

=item * C&lt;set_attr($name,$value)&gt;

This method will set the value of an attribute.  If the attribute is not found,
then C&lt;get_attrseq()&gt; will have the new attribute listed at the end.

 # &lt;p&gt;
 $token-&gt;set_attr(class =&gt; 'some_class');
 print $token-&gt;as_is;
 # &lt;p class="some_class"&gt;

 # &lt;body bgcolor="#FFFFFF"&gt;
 $token-&gt;set_attr('bgcolor','red');
 print $token-&gt;as_is;
 # &lt;body bgcolor="red"&gt;

After this method is called, if successful, the C&lt;as_is()&gt;, C&lt;get_attr()&gt;
and C&lt;get_attrseq()&gt; methods will all return updated results.

=item * C&lt;set_attr($hashref)&gt;

Under the premise that C&lt;set_&gt; methods should accept what their corresponding
C&lt;get_&gt; methods emit, the following works:

  $tag-&gt;set_attr($tag-&gt;get_attr);

Theoretically that's a no-op and for purposes of rendering HTML, it should be.
However, internally this calls C&lt;$tag-E&lt;gt&gt;rewrite_tag&gt;, so see that method to
understand how this may affect you.

Of course, this is useless if you want to actually change the attributes, so you
can do this:

  my $attrs = {
    class  =&gt; 'headline',
    valign =&gt; 'top'
  };
  $token-&gt;set_attr($attrs) 
    if $token-&gt;is_start_tag('td') &amp;&amp;  $token-&gt;get_attr('class') eq 'stories';

=item * C&lt;rewrite_tag()&gt;

This method rewrites the tag.  The tag name and the name of all attributes will
be lower-cased.  Values that are not quoted with double quotes will be.  This
may be called on both start or end tags.  Note that both C&lt;set_attr()&gt; and
C&lt;delete_attr()&gt; call this method prior to returning.

If called on a token that is not a tag, it simply returns.  Regardless of how
it is called, it returns the token.

 # &lt;body alink=#0000ff BGCOLOR=#ffffff class='none'&gt;
 $token-&gt;rewrite_tag;
 print $token-&gt;as_is;
 # &lt;body alink="#0000ff" bgcolor="#ffffff" class="none"&gt;

A quick cleanup of sloppy HTML is now the following:

 my $parser = HTML::TokeParser::Simple-&gt;new( string =&gt; $ugly_html );
 while (my $token = $parser-&gt;get_token) {
     $token-&gt;rewrite_tag;
     print $token-&gt;as_is;
 }

=back

=head1 PARSER VERSUS TOKENS 

The parser returns tokens that are blessed into appropriate classes.  Some
people get confused and try to call parser methods on tokens and token methods
on the parser.  To prevent this, C&lt;HTML::TokeParser::Simple&gt; versions 1.4 and
above now bless all tokens into appropriate token classes.  Please keep this in
mind while using this module (and many thanks to PodMaster
L&lt;http://www.perlmonks.org/index.pl?node_id=107642&gt; for pointing out this issue
to me.)

=head1 EXAMPLES

=head2 Finding comments

For some strange reason, your Pointy-Haired Boss (PHB) is convinced that the
graphics department is making fun of him by embedding rude things about him in
HTML comments.  You need to get all HTML comments from the HTML.

 use strict;
 use HTML::TokeParser::Simple;

 my @html_docs = glob( "*.html" );

 open PHB, "&gt; phbreport.txt" or die "Cannot open phbreport for writing: $!";

 foreach my $doc ( @html_docs ) {
     print "Processing $doc\n";
     my $p = HTML::TokeParser::Simple-&gt;new( file =&gt; $doc );
     while ( my $token = $p-&gt;get_token ) {
         next unless $token-&gt;is_comment;
         print PHB $token-&gt;as_is, "\n";
     }
 }

 close PHB;

=head2 Stripping Comments

Uh oh.  Turns out that your PHB was right for a change.  Many of the comments
in the HTML weren't very polite.  Since your entire graphics department was
just fired, it falls on you need to strip those comments from the HTML.

 use strict;
 use HTML::TokeParser::Simple;

 my $new_folder = 'no_comment/';
 my @html_docs  = glob( "*.html" );

 foreach my $doc ( @html_docs ) {
     print "Processing $doc\n";
     my $new_file = "$new_folder$doc";

     open PHB, "&gt; $new_file" or die "Cannot open $new_file for writing: $!";

     my $p = HTML::TokeParser::Simple-&gt;new( $file =&gt; doc );
     while ( my $token = $p-&gt;get_token ) {
         next if $token-&gt;is_comment;
         print PHB $token-&gt;as_is;
     }
     close PHB;
 }

=head2 Changing form tags

Your company was foo.com and now is bar.com.  Unfortunately, whoever wrote your
HTML decided to hardcode "http://www.foo.com/" into the C&lt;action&gt; attribute of
the form tags.  You need to change it to "http://www.bar.com/".

 use strict;
 use HTML::TokeParser::Simple;

 my $new_folder = 'new_html/';
 my @html_docs  = glob( "*.html" );

 foreach my $doc ( @html_docs ) {
     print "Processing $doc\n";
     my $new_file = "$new_folder$doc";

     open FILE, "&gt; $new_file" or die "Cannot open $new_file for writing: $!";

     my $p = HTML::TokeParser::Simple-&gt;new( file =&gt; $doc );
     while ( my $token = $p-&gt;get_token ) {
         if ( $token-&gt;is_start_tag('form') ) {
             my $action = $token-&gt;get_attr(action);
             $action =~ s/www\.foo\.com/www.bar.com/;
             $token-&gt;set_attr('action', $action);
         }
         print FILE $token-&gt;as_is;
     }
     close FILE;
 }

=head1 CAVEATS

For compatability reasons with C&lt;HTML::TokeParser&gt;, methods that return
references are violating encapsulation and altering the references directly
B&lt;will&gt; alter the state of the object.  Subsequent calls to C&lt;rewrite_tag()&gt;
can thus have unexpected results.  Do not alter these references directly
unless you are following behavior described in these docs.  In the future,
certain methods such as C&lt;get_attr&gt;, C&lt;get_attrseq&gt; and others may return a
copy of the reference rather than the original reference.  This behavior has
not yet been changed in order to maintain compatability with previous versions
of this module.  At the present time, your author is not aware of anyone taking
advantage of this "feature," but it's better to be safe than sorry.

Use of C&lt;$HTML::Parser::VERSION&gt; which is less than 3.25 may result in
incorrect behavior as older versions do not always handle XHTML correctly.  It
is the programmer's responsibility to verify that the behavior of this code
matches the programmer's needs.

Note that C&lt;HTML::Parser&gt; processes text in 512 byte chunks.  This sometimes
will cause strange behavior and cause text to be broken into more than one
token.  You can suppress this behavior with the following command:

 $p-&gt;unbroken_text( [$bool] );

See the C&lt;HTML::Parser&gt; documentation and
http://www.perlmonks.org/index.pl?node_id=230667 for more information.

=head1 BUGS

There are no known bugs, but that's no guarantee.

Address bug reports and comments to: E&lt;lt&gt;eop_divo_sitruc@yahoo.comE&lt;gt&gt;.  When
sending bug reports, please provide the version of C&lt;HTML::Parser&gt;,
C&lt;HTML::TokeParser&gt;, C&lt;HTML::TokeParser::Simple&gt;, the version of Perl, and the
version of the operating system you are using.

Reverse the name to email the author.

=head1 SUBCLASSING

You may wish to change the behavior of this module.  You probably do not want
to subclass C&lt;HTML::TokeParser::Simple&gt;.  Instead, you'll want to subclass one
of the token classes.  C&lt;HTML::TokeParser::Simple::Token&gt; is the base class for
all tokens.  Global behavioral changes should go there.  Otherwise, see the
appropriate token class for the behavior you wish to alter.

=head1 SEE ALSO

L&lt;HTML::TokeParser::Simple::Token&gt;

L&lt;HTML::TokeParser::Simple::Token::Tag&gt;

L&lt;HTML::TokeParser::Simple::Token::Text&gt;

L&lt;HTML::TokeParser::Simple::Token::Comment&gt;

L&lt;HTML::TokeParser::Simple::Token::Declaration&gt;

L&lt;HTML::TokeParser::Simple::Token::ProcessInstruction&gt;

=head1 COPYRIGHT

Copyright (c) 2004 by Curtis "Ovid" Poe.  All rights reserved.  This program is
free software; you may redistribute it and/or modify it under the same terms as
Perl itself

=head1 AUTHOR

Curtis "Ovid" Poe E&lt;lt&gt;eop_divo_sitruc@yahoo.comE&lt;gt&gt;

Reverse the name to email the author.

=cut
</pre></body></html>