Perl 的 Object::Destroyer

使用 HTML::Tree 時因為有 circular reference,會要求你要使用 ->delete() 告知 object 打斷 reference 以避免 memory leak。於是就得很小心寫,要注意每個步驟以免某些狀況下忘記 ->delete() 而造成 leak:

my $html = HTML::TreeBuilder->new_from_content($body);
foreach my $element ($html->look_down('a', qr{某個 RE 條件})) {
    if (符合某個條件) {
        # 做某些事情...

        $element->delete;
        $html->delete;
        return;
    }

    # 做某些事情...
    $element->delete;
}
$html->delete;

後來找到了 Object::Destroyer,利用另外一個 object 的存活幫忙回收,於是就可以簡化成:

my $html = HTML::TreeBuilder->new_from_content($body);
my $htmlD = Object::Destroyer->new($html, 'delete');
foreach my $element ($html->look_down('a', qr{某個 RE 條件})) {
    my $elementD = Object::Destroyer->new($element, 'delete');
    if (符合某個條件) {
        return;
    }
    # 做某些事情...
}

這樣就不會 leak 了...

Leave a Reply

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