Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,

I am trying to insert the "$new_tag" value into the "$src" string, immediately after the "<record name="rightnav" type="content">" . The "$new_tag" is getting inserted but not at the desired position.

Please advice

$src ='<?xml version="1.0" encoding="UTF-8"?><record name="rightnav" t +ype="content"><item name="RHS_Image"><value>/me/accounts/include/imag +es/accounts_RHS.jpg</value> </item> <item name="RHS_Navigation">';
$new_tag ='<item name="abcd"><value>'; if($strFile =~ /<record (.*)>/igm){ $strFile =~ s/$&/$&$new_tag/i; }

Thanks in advance

Replies are listed 'Best First'.
Re: Insert into string
by Samy_rio (Vicar) on Jul 22, 2005 at 07:11 UTC

    Hi, change your if statement as follows:

    if($src =~ /<record[^>]*>/igm){ $src =~ s/$&/$&$new_tag/i; }

    Regards,
    Velusamy R.

      Hi ,

      Printing $& will output the following

      <record name="rightnav" type="content"><item name="RHS_Image">

      Which means the $new_tag will be appended after the "item" tag. Which is now what is intended.

      The "$new_tag" is aimed to be inserted after the "<record name="rightnav" type="content">" tags.

      Thanks

Re: Insert into string
by Cody Pendant (Prior) on Jul 22, 2005 at 08:12 UTC
    Someone has to say it. You appear to be editing XML, and therefore you'd be better off, in the long run, using an XML module to Do It Properly.


    ($_='kkvvttuu bbooppuuiiffss qqffssmm iibbddllffss')
    =~y~b-v~a-z~s; print
Re: Insert into string
by gopalr (Priest) on Jul 22, 2005 at 08:34 UTC

    Hello

    You did 2 mistakes in ur coding. That is:

    1. Your variable name is wrong. $strFile variable not contains any text. so do change it to $src.

    2. ? missing in <record (.*)>

    $src ='<?xml version="1.0" encoding="UTF-8"?><record name="rightnav" t +ype="content"><item name="RHS_Image"><value>/me/accounts/include/imag +es/accounts_RHS.jpg</value> </item> <item name="RHS_Navigation">'; $new_tag ='<item name="abcd"><value>'; if($src =~ /<record (.*?)>/igm){ $src=~ s/$&/$&$new_tag/i; } print "\n$src";

    Output:

    <?xml version="1.0" encoding="UTF-8"?><record name="rightnav" type="co +ntent"><it em name="abcd"><value><item name="RHS_Image"><value>/me/accounts/inclu +de/images/ accounts_RHS.jpg</value> </item> <item name="RHS_Navigation">
A reply falls below the community's threshold of quality. You may see it by logging in.