How To Fix a Perl Memory Leak

If you’re using HTML::TreeBuilder, you might find a memory leak when creating lots of trees. You must explicitly delete the trees because HTML::Tree does not use weak refs. Here’s how to delete the ref:

use HMTL::TreeBuilder;

my $formatter = HTML::FormatText->new();

my $html_tree = HTML::TreeBuilder->new_from_content($line);
my $plain_text = $formatter->format($html_tree);
$html_tree->delete();

Or if you use HTML::Parse:

my $html_tree = parse_html($line);
$html_tree->eof();
my $plain_text = HTML::FormatText->new()->format($html_tree);
$html_tree->delete();

Or using Object::Destroyer

use Object::Destroyer;

my $html_tree = parse_html($line);
$html_tree = Object::Destroyer->new($html_tree, ‘delete’);
$html_tree->eof();

my $plain_text = HTML::FormatText->new->format($html_tree);

Source: perlmonks.org

This entry was posted in Perl. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>