As the others already pointed out, HTML::Parser or one of its subclasses is the way to go. Here i use HTML::Toke parser, saves you some work.
The code below is not equiv. to yours but something to get you started.
use strict;
use HTML::TokeParser;
use Data::Dumper;
my %tokens;
my %tokencount;
my $p = HTML::TokeParser->new("test.html") or die "Can't open: $!";
while (my $token = $p->get_token)
{
if ( $token->[0] eq "S" )
{
$tokens{$token->[1]}++
unless $token->[1] =~ /meta/i;
}
elsif ( $token->[0] eq "E" )
{
$tokens{$token->[1]}--;
}
elsif ( $token->[0] eq "T" )
{
my @words = ( $token->[1] =~ /\b(\w+)/g );
for ( keys %tokens )
{
$tokencount{$_} += @words
if $tokens{$_} > 0;
}
}
}
print Dumper (\%tokencount);
When test.html looks like
<html lang='en-US'>
<head>
<title>Stuff</title>
<meta name='author' content='Jojo' />
</head>
<body>
<h2>I like potatoes!</h2>
<h1>Me not!</h1>
</body>
</html>
it will print
$VAR1 = {
'h1' => 2,
'body' => 5,
'head' => 1,
'html' => 6,
'title' => 1,
'h2' => 3
};
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.