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

Dear Perl experts,
input file test.txt:
<table1><tgroup cols="3"></table1> <table2><tgroup cols="2"></table2>
output file test.out:
<table1><tgroup cols="3"> <colspec colnum='1' colname='1'/> <colspec colnum='2' colname='2'/> <colspec colnum='3' colname='3'/> </table1> <table2><tgroup cols="2"> <colspec colnum='1' colname='1'/> <colspec colnum='2' colname='2'/> </table2>
i want to print <colspec..> N number of times just after <tgroup cols="N"> depending upon the value N found inside <tgroup cols="N">.
But my following code prints the output outside somewhere
my %tval; open(IN, "<test.txt") || die "\nCan't open test.txt\n $!\n"; open(OUT, ">test.out") || die "\nCan't open test.out\n $!\n"; while(<IN>) { if(/<tgroup cols="(.*?)">/) { for ($count = 1; $count <= $1; $count++) { print OUT "<colspec colnum='$count' colname='$count'/>\n"; } } print OUT; } close(IN); close(OUT);
pls help me in fixing the code.

Replies are listed 'Best First'.
Re: for loop
by ikegami (Patriarch) on Aug 11, 2008 at 06:49 UTC
    while (<IN>) { s{(<tgroup cols="(.*?)">)}{ "$1\n" . (map { "<colspec colnum='$_' colname='$_'/>\n" } 1..$2) }eg; print OUT; }
      hi, thanks for your time and help
      but the code
      while (<IN>) { s{(<tgroup cols="(.*?)">)}{ "$1\n" . (map { "<colspec colnum='$_' colname='$_'/>\n" } 1..$2) }eg; print OUT; }
      just prints <table><tgroup cols="3">3</table>
        Oops!
        while (<IN>) { s{(<tgroup cols="(.*?)">)}{ "$1\n" . join('', map { "<colspec colnum='$_' colname='$_'/>\n" } 1..$2) }eg; print OUT; }
Re: for loop
by Anonymous Monk on Aug 11, 2008 at 06:45 UTC
    print OUT;
    prints the contents of $_, which happen to be an entire line.