saurabh.x.pandey has asked for the wisdom of the Perl Monks concerning the following question:

I have one file file.xml. and I am trying to modify the text of tag h<ref> if it's attribute val +ue is cde. <?xml version='1.0'?> <root> <test> <name>file</name> <href attr="abc">saur</href> </test> <test> <name>file1</name> <href attr="cde">mand</href> </test> </root> I have written a code as: use XML::Twig; use Data::Dumper; my $xml=$ARGV[0]; my $tag_name=$ARGV[1]; my $att_name=$ARGV[2]; my $att_value=$ARGV[3]; my $tag_text=$ARGV[4]; my $twig = XML::Twig->new(twig_roots => {$tag_name => \&select_change +}, ); $twig->parsefile_inplace($xml); $twig->flush; sub select_change { my($twig,$tag_name)=@_; if ($tag_name->att('$att_name') =~ "$att_value") { $tag_name->set_text('$tag_text'); } } Now I am giving command line as perl -w twigparse.pl file.xml href attr cde sriram Now it is not running but if I give values to all command line variabl +es in program then it runs.Please correcr me.I am stuck in this code. +..Help me........

Replies are listed 'Best First'.
Re: XML::Twig parsing Problem
by pobocks (Chaplain) on Dec 02, 2008 at 10:42 UTC

    I'm afraid I don't have the solution to your problem, but you're more likely to get a useful response if you reformat your node some.

    At the very least, pull your question and explanation out of the code tags and put them in paragraphs, and get rid of the double spacing.

    for(split(" ","tsuJ rehtonA lreP rekcaH")){print reverse . " "}print "\b.\n";
      sub select_change { my($twig,$tag_name)=@_; if ($tag_name->att('$att_name') =~ "$att_value") { $tag_name->set_text('$tag_text'); } }
      Actually I have problem on one point. my($twig,$tag_name)=@_; the value of $tag_name=href so in place of $tag_name the value should be $href. for that I tried as my($twig,${$tag_name)}=@_; but it's not working...so what is the solution to do it.

        I don't quite understand the question, but the arguments to the handler are the twig itself and the element object, not its tag name. So if you want to change the name of the element, you need $tag->set_tag( ...).

        Also, the single quotes in '$tag_text' prevent interpolation (you will get the literal text $tag_text), get rid of them and you will get the value of $tag_text.