I want to extract all the html between the tag of a string or file Ive been looking at using (perl) with the module html::parser, I thought this would be a simple task but its turning out to be quite tricky? I found some code which works but dont know how to save results to a string ?? any help appreciated or if you can show me some code on how this can be achived using HTML::TokeParser or similar.
Thanks
my $content=<<EOF;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some title goes here</title>
</head>
<body bgcolor="#FFFFFF">
<div id="leftcol">
menu column
</div>
<div id="body">
<p>some text goes here some text goes here<br />
some text goes here some text goes here</p>
<p><strong>some header</strong></p>
<p>some text goes here some text goes here<br />
some text goes here some text goes here</p>
<p><img src="img.gif" /> image here</p>
<p><strong>some header</strong></p>
<p>some text goes here some text goes here<br />
some text goes here some text goes here</p>
</div>
<div id="rightcol">
news column
</div>
</body>
</html>
EOF
my $p = HTML::Parser->new( api_version => 3 );
$p->handler( start => \&start_handler, "self,tagname,attr" );
$p->parse($content);
exit;
sub start_handler {
my $self = shift;
my $tagname = shift;
my $attr = shift;
my $text = shift;
return unless ( $tagname eq 'body' );
$self->handler( start => sub { print shift }, "text" );
$self->handler( text => sub { print shift }, "text" );
$self->handler( end => sub {
my ($endtagname, $self, $text) = @_;
if($endtagname eq $tagname) {
$self->eof;
} else {
print $text;
}
}, "tagname,self,text");
}
if i modify the above Sub routine start text and end handlers like below
why doesnt the text from those varibles get saved in mine ?
$self->handler( start => sub { my ($text) = @_; $inner_body = $inner_body. $text; }, "text" );
$self->handler( text => sub { my ($text) = @_; $inner_body = $inner_body. $text; }, "text" );
$self->handler( end => sub {
my ($endtagname, $self, $text) = @_;
if($endtagname eq $tagname) {
$self->eof;
} else {
$inner_body = $inner_body. $text;
}
}, "tagname,self,text");
}
print $inner_body; # <-- prints blank ???
Desired output to be saved in varible
<div id="leftcol">
menu column
</div>
<div id="body">
<p>some text goes here some text goes here<br />
some text goes here some text goes here</p>
<p><strong>some header</strong></p>
<p>some text goes here some text goes here<br />
some text goes here some text goes here</p>
<p><img src="img.gif" /> image here</p>
<p><strong>some header</strong></p>
<p>some text goes here some text goes here<br />
some text goes here some text goes here</p>
</div>
<div id="rightcol">
news column
</div>
exit(0); print $inner_body;prints blank?