下面的程序给了我奇怪的输出,我无法解释:
use strict;
use warnings;
use XML::Twig;
my $xml =
q{<block>
<foo>bar baz</foo>
</block>};
my $twig = XML::Twig->new(
TwigHandlers => {foo => \&foo, block => \&block},
);
print "after parse: " . $twig->parse($xml)->sprint;
sub foo {
my ( $twig, $foo ) = @_;
my $text = $foo->sprint("don't print outside element");
my $newSummary = XML::Twig::Elt->parse( '<p><i>' . $text . '</i></p>' );
$newSummary->paste( 'before', $foo);
my $parent = $foo->parent;
# $foo->delete;
print "foo: " . $parent->sprint . "\n\n";
}
sub block {
my ($twig, $block) = @_;
print "block: " . $block->sprint . "\n\n";
}
它打印以下内容:
foo: <block><p><i>bar baz</i></p><foo>bar baz</foo></block>
block: <block><p><i>bar baz</i></p><foo>bar baz</foo></block>
after parse: <block><foo>bar baz</foo></block>
所以我正在修改foo
处理程序内部的树枝,更改是为了block
处理程序来查看它,但是当处理完成后,更改就会消失。这里发生了什么?如何在枝条的整个生命周期内改变我的变化?
答案 0 :(得分:1)
你没有归还任何东西。删除子例程中的print语句,您将获得以下输出:
after parse: <block><p><i>bar baz</i></p><foo>bar baz</foo></block>