Human has asked for the wisdom of the Perl Monks concerning the following question:
My code (trimmed way down to just show the problem):<?xml version="1.0" ?> <tcf> <tweak name = "T1"> <description>D1</description> </tweak> <tweak name = "T2"> <description>D2</description> </tweak> <tweak name = "T3"> <description>D3</description> </tweak> <tweak name = "T2"> <description>This should overwrite the old T2.</description> </tweak> </tcf>
When I run that code on that XML file, here is the output:#!/usr/bin/perl use strict; use XML::Twig; # As each tweak tag is processed, this subroutine is called. Here we +will # see if any previous tweak tag had the same name element. If so, we +will # overwrite the previous tweak tag with this new tweak tag's contents, + then # delete the new tweak tag. sub pruner { my $this_tweak = $_; my $tweakname = $this_tweak->att('name'); my $exp = "/tcf/tweak[\@name=\"$tweakname\"]"; my @matches = $this_tweak->get_xpath($exp); print "TWEAK: "; $this_tweak->print; print " (Found $#matches other parsed tweaks with the same name)\n +"; # If the tweak's name is found elsewhere, replace the first # instance with the latest one, then delete the latest one. if ($#matches == 1) { print "\tReplacing\n\t\t"; @matches[0]->print; print "\n\twith\n\t\t"; $this_tweak->print; print "\n"; $this_tweak->replace(@matches[0]); } } my $twig = XML::Twig->new(expand_external_ents => 1, twig_handlers => { 'tweak' => \&pruner } ); $twig->parsefile("/home/igo/StormLogic/MythiC/Tweaker/test5.tcf"); print "TWIG:\n"; $twig->print; print "\n";
It should print the Twig at the end, but it gets stuck. Am I abusing the replace method and/or putting the Twig into a broken state? This is one particular instance of the problems I've had trying this sort of thing. I wanted to understand what I'm doing wrong with this tiny example first so I can tackle the larger case on my own. Thanks!$ ./twig_replace_test.pl TWEAK: <tweak name="T1"><description>D1</description></tweak> (Found 0 + other parsed tweaks with the same name) TWEAK: <tweak name="T2"><description>D2</description></tweak> (Found 0 + other parsed tweaks with the same name) TWEAK: <tweak name="T3"><description>D3</description></tweak> (Found 0 + other parsed tweaks with the same name) TWEAK: <tweak name="T2"><description>This should overwrite the old T2. +</description></tweak> (Found 1 other parsed tweaks with the same nam +e) Replacing <tweak name="T2"><description>D2</description></tweak> with <tweak name="T2"><description>This should overwrite the old T2 +.</description></tweak> TWIG:
|
|---|