Why does XML :: Twig print the extracted string twice?

Why do I get my string twice in the output?

#!/usr/bin/perl
use warnings;
use strict;

use XML::Twig;


my $string = '<cd_catalogue><title>Hello, World!</title></cd_catalogue>';

my $t= XML::Twig->new(  twig_handlers   => { cd_catalogue => \&cd_catalogue, },
            pretty_print => 'indented', 
);

$t->parse( $string );


sub cd_catalogue {
    my( $t, $cd_catalogue ) = @_;
    $cd_catalogue->flush;
}


# Output:
#<cd_catalogue>
#  <title>Hello, World!</title>
#</cd_catalogue>
#<cd_catalogue>
#  <title>Hello, World!</title>
#</cd_catalogue>
+3
source share
2 answers

Changing your subuser to use printand purgeinstead flushfixes the problem:

sub cd_catalogue {
    my( $t, $cd_catalogue ) = @_;
    $cd_catalogue->print;
    $cd_catalogue->purge;
}

flushconfused because of the simplicity of your example, because it cd_catalogueis the root node. If you change your data to the following:

my $string = '
    <cds>
        <cd_catalogue><title>Hello, World!</title></cd_catalogue>
    </cds>';

or if you changed your twig_handler to search title:

twig_handlers    => { title => \&cd_catalogue }

then you will find that it $cd_catalogue->flushnow works as expected with yours $string.

/ I3az /

+4
source

XML:: Twig. " , ".

cd_catalogue

sub cd_catalogue {
    my( $t, $cd_catalogue ) = @_;
    $t->flush;
}

.

+4

Source: https://habr.com/ru/post/1727589/


All Articles