use warnings; use strict; use XML::Twig; # Generate the XML file my $str = do {local $/; }; open OUT, '>', 'temp.xml'; print OUT $str; close OUT; # Troublesome code print "******* Troublesome version\n"; my @fileList = qw(first second third); my $sub = bindArgs (\&insertFiles, \@fileList); my $twig = XML::Twig->new ( discard_spaces => 1, pretty_print => 'indented', twig_roots => {'sourceFiles' => $sub,}, # Insert file list twig_print_outside_roots => 1, # Print the rest ); $twig->parsefile ('temp.xml'); # Ok code print "******* Ok version\n"; $twig = XML::Twig->new ( discard_spaces => 1, pretty_print => 'indented', twig_roots => {'sourceFiles' => $sub,}, # Insert file list twig_print_outside_roots => 1, # Print the rest ); $twig->parse ($str); sub bindArgs { my ($sub, @args) = @_; return sub {$sub->(@args, @_);}; } sub insertFiles { my ($sourceFiles, $twig, $node) = @_; for (@$sourceFiles) { my $eFile = $twig->root->new (sourcefile => $_); # create the element $eFile->paste (first_child => $node); } $node->print (); } __DATA__ arm_pulse.dat bp_Ex1.dat bp_pulse.dat cuff practice.dat #### ******* Troublesome version third second first arm_pulse.dat bp_Ex1.dat bp_pulse.dat cuff practice.dat ******* Ok version third second first arm_pulse.dat bp_Ex1.dat bp_pulse.dat cuff practice.dat