Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Inplace edit using XML::Twig

by GrandFather (Cardinal)
on May 21, 2006 at 23:32 UTC ( #550838=perlquestion: print w/ replies, xml ) Need Help??
GrandFather has asked for the wisdom of the Perl Monks concerning the following question:

Is there a way to inplace edit using XML::Twig, or have I got to go through the pain of creating a temporary file and replacing the original? Is there a better way to do that than the following?

# Edit the manifest my $saveStdOut = select; my $manifestOut; open $manifestOut, '>', "$manifestPath.new"; select $manifestOut; $sub = bindArgs (\&insertFiles, $absDir, \@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 ($manifestPath); select $saveStdOut; close $manifestOut; unlink $manifestPath; rename $manifestPath . '.new', $manifestPath;

DWIM is Perl's answer to Gödel

Comment on Inplace edit using XML::Twig
Download Code
Re: Inplace edit using XML::Twig
by kvale (Monsignor) on May 22, 2006 at 03:40 UTC
    Why not just read in the file contents, truncate the file, and write processed file contents back out to the same file? No delete and rename needed.

    -Mark

      Tim Bray makes some suggestions why you might not want to do that here, the caveat being of course how important is the data in question.

      --
      Do not seek to follow in the footsteps of the wise. Seek what they sought. -Basho

      There are two reasons, firstly renaming is an atomic operation on all the systems that I am aware of so there is no risk of another application that can't be made to co-operate with this one getting a partially written file, secondly writing to a second file mitigates against the risk of the file being corrupted if the process is interrupted due to a program or OS crash or hardware failure for instance. For the most part I would omit the deletion stage to further reduce the risk of losing the file (although some OS might not support this).

      /J\

Re: Inplace edit using XML::Twig
by mirod (Canon) on May 22, 2006 at 10:02 UTC
      Life would be so much harder without XML::Twig - nice one!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://550838]
Approved by polettix
Front-paged by monkfan
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2014-08-29 05:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (275 votes), past polls