How to save a modified tree to disk using XML Twig

Tried this below, but I get file 0 and this error. print () on an unopened file descriptor OUT on C: /Perl/site/lib/XML/Twig.pm line 3036.

#!c:\perl\bin\perl.exe
use strict;
use XML::Twig;

my $upd_file = "updev.xml" ;
my $main_file = "main.xml" ;

# get the info we need by loading the update file
my $t_upd= new XML::Twig();

$t_upd->parsefile( $upd_file);

my $upd_dev_id = $t_upd->root->next_elt( 'DEVNUM')->text;
my $upd_dev    = $t_upd->root->next_elt( 'DEVS');
my $upd_seg    = $t_upd->root ;

# now process the main file
my $t= new XML::Twig( TwigHandlers => { DEVS => \&DEVS, },
              PrettyPrint => 'indented',
            );
$t->parsefile( $main_file);
$t->flush;           # don't forget or the last closing tags won't be printed

open( OUT, ">$main_file") or die "cannot open out file main_file:$!";

sub DEVS
  { my( $t, $DEVS)= @_;
    # just replace devs if the previous dev_id is the right one
    if( $DEVS->prev_elt( 'DEVNUM')->text eq $upd_dev_id) {
      $upd_dev->replace($DEVS);    
    }
     $t->flush(\*OUT) ;  # print and flush memory so only one dev is in there at once

  }

close OUT ;
+3
source share
1 answer

Probably your problem is that you did not pass the file descriptor to a file reference.

$t->flush(\*OUT) # look at the '\'

Some suggestions for your code: in modern perl, it is better to use three arguments to open and indirect file descriptors:

open (my $fh_out, '>', $out_file) or die "unable to open '$out_file' for writing: $!";

$twig->print($fh_out); # this prints to the filehandle

Another way to print is to bind your tree with $twig->sprintand print to a file as usual

 print {$fh_out} $twig->sprint();
+5
source

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


All Articles