Perl中的弱引用

如何在perl中创建对象的弱引用,所以当对象超出范围时,引用计数被释放?
我已经尝试使用DESTROY子来打破循环引用.

sub DESTROY{  
my $p = shift;  
delete $p->{__tree__};  
delete $p->{tokenizers};  
delete $p->{toke};  
}

请帮忙.

解决方法

你不能“调用”破坏 – 这里的问题是perl在引用计数上工作 – 对事物的每个引用都被计算,并且只有当引用计数降到零时才会被释放/销毁/垃圾收集.

DESTROY是一种特殊方法,在发生这种情况时,在对象内调用以执行清理任务.它不会删除对象,它只是让它在它死亡时做一些最后的整理.

看看Scalar::Util模块.它包括弱化方法,它完全符合您的要求.

The lvalue $ref will be turned into a weak reference. This means that it will not hold a reference count on the object it references. Also when the reference count on that object reaches zero,the reference will be set to undef. This function mutates the lvalue passed as its argument and returns no value.

This is useful for keeping copies of references,but you don’t want to prevent the object being DESTROY-ed at its usual time.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...