BenHopkins has asked for the wisdom of the Perl Monks concerning the following question:

I'm getting funny results. Don't know how it can happen. I'm updating the xml. Open output file. Using new technique to pass extra args to twig handlers. Passing the filehandle to twig handler, and to twig_print_outside_roots.

It all works, except I put a debug print statement in the handler. It prints to STDOUT, but it doesn't go there, it goes into the output xml.

Here's a code snippet:

open(OUT, ">$tmpdir/$fname") or die "Can't open output $tmpdir/$fname: $!\n"; my $twig = XML::Twig->new(twig_roots => { '/object/attributes/attribute' => sub { put_new_jump(@_, \*OUT, $path) }, }, twig_print_outside_roots => \*OUT, keep_encoding => 1, ); sub put_new_jump { my ($tree, $elem, $fh, $path) = @_; my $name = $elem->att('name'); print "Name: $name\n"; <blah blah blah> $elem->print($fh); }
See that 'print_outside_roots => \*OUT' works, and $elem->print($fh) works. But why is STDOUT also being redirected into the xml? Oh, here's what part of the xml looks like:
Name: CreateTime <attribute group="Graph" kind="integer" name="CreateTime">1250716389</ +attribute> Name: RevOperator <attribute group="Graph" kind="string" name="RevOperator">jwalton</att +ribute> Name: Uid <attribute group="Graph" kind="string" name="Uid">PS4PS9S</attribute> Name: DataRevisionDate <attribute group="Graph" kind="integer" name="DataRevisionDate">125080 +1191</attribute>

Replies are listed 'Best First'.
Re: XML::Twig and STDOUT??
by GrandFather (Saint) on Aug 28, 2009 at 00:52 UTC

    XML::Twig uses select internally to redirect print output which is mucking up your use of print - that's getting redirected too. You could work around it by using STDOUT explicitly in yout diagnostic print:

    use strict; use warnings; use XML::Twig; my $outStr = ''; open my $outFile, '>', \$outStr; my $twig = XML::Twig->new ( twig_roots => {'wibble' => sub {put_new_jump (@_, $outFile, 'wibbl +e')}}, twig_print_outside_roots => $outFile, keep_encoding => 1, ); $twig->parse (<<XML); <root> <wibble name='My Name is Mr. Wibble'>The wibble element</wibble> </root> XML close $outFile; print "All done now. Result is:\n\n"; print $outStr; sub put_new_jump { my ($tree, $elem, $fh, $path) = @_; my $name = $elem->att ('name'); print STDOUT "Name: $name\n"; $elem->print ($fh); }

    Prints:

    Name: My Name is Mr. Wibble All done now. Result is: <root> <wibble name="My Name is Mr. Wibble">The wibble element</wibble> </root>

    True laziness is hard work
      That did it. Thanks. An un-documented side effect, I guess.
Re: XML::Twig and STDOUT??
by ikegami (Patriarch) on Aug 28, 2009 at 00:53 UTC
    Maybe Twig selected $fh? If so, you can get around it by printing to STDOUT explicitly.
    print STDOUT ...; print(STDOUT ...); STDOUT->print(...);
      You got it. That's what it must have done. Thank you very much.