copy perl object ref
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 trie开发者_开发百科d 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!!
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:
my $html1 = HTML::PullParser->new(file => $file, text => 'text');
my $html2 = HTML::PullParser->new(file => $file, text => 'text');
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.
精彩评论