复制 perl 对象引用
如何复制/克隆已“祝福”的对象引用?例如,我
my $html = HTML::PullParser->new(file => $file, text => 'text');
想通过多次迭代该 $html
对象
$html->get_token();
所以我尝试做的是首先复制该对象:
use Clone qw(clone);
my $html1 = clone($html);
my $html2 = clone($html);
然后我尝试迭代新对象:
while ($html1->get_token()) {
# do something
}
while ($html2->get_token()) {
# do something else
}
但显然该对象没有被复制(或者至少没有以正确的方式复制),因此我在两个循环中都没有得到任何迭代。
复制这个对象的正确方法是什么?
谢谢!!
How do I copy/clone an object ref that has been "blessed"? For example, I have
my $html = HTML::PullParser->new(file => $file, text => 'text');
then I want to iterate over that $html
object multiple times via
$html->get_token();
So what I tried to do is to copy the object first:
use Clone qw(clone);
my $html1 = clone($html);
my $html2 = clone($html);
Then I tried to iterate over the new objects:
while ($html1->get_token()) {
# do something
}
while ($html2->get_token()) {
# do something else
}
But clearly the object is NOT copied over (or at least not copied over in the right way) so that I do not get any iteration in either loop.
What is the right way to copy this object?
Thx!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,克隆一个对象需要了解其内部结构。 Clone 只是复制内部结构,它适用于普通数据结构和许多对象,但在更多对象上失败以不可预测的方式复杂的对象。
在本例中, HTML::PullParser 对象正在从文件句柄读取。克隆的副本获取对相同文件句柄的引用,因此它们不是独立的。
某些对象具有
clone
方法,但 HTML::PullParser 没有。您可以创建多个对象:并且它们将是独立的。或者您是否试图在解析过程中克隆对象?也许您可以解释为什么您认为需要克隆解析器,我们可以建议更好的方法。
In general, cloning an object requires knowledge of its internal structure. Clone just copies the internal structure, which works on plain data structures and many objects, but fails on more complex objects in unpredictable ways.
In this case, the HTML::PullParser object is reading from a filehandle. The cloned copy gets a reference to the same filehandle, so they are not independent.
Some objects have a
clone
method, but HTML::PullParser does not. You can create multiple objects:and they will be independent. Or are you trying to clone the object in the middle of parsing? Perhaps you can explain why you think you need to clone the parser and we can suggest a better approach.