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

Hi,

Is there an even cooler way to this?

Here I am reading the file keywords.txt. the format is:

filename minus extension \t keywords to add to file.

the idea is to open the file (adding .xml) and inserting the keywords element at the 4th line.

Feels like I should be able to localize $^I and make use of the diamond operator to then edit each file in place.

perl -F'\t' -ane 'open (A, "$F[0].xml"); open(B, ">$F[0]") ;while(<F>) + { print B; if ($.==4) { print B " <keywords> ".substr($F[1],0,-1)." + </keywords>\n" ; }} close(A); close(B); unlink("$F[0].xml"); rename( +$F[0], "$F[0].xml");' keywords.txt

less is more!

thanks,

Josh

20050930 Janitored by Corion: Added formatting

Replies are listed 'Best First'.
Re: inline replace
by graff (Chancellor) on Sep 30, 2005 at 23:41 UTC
    Is there an even cooler way to this?

    You mean, is there some other way that is less brittle, ad-hoc and prone to outrageous failure? I should hope so.

    But it would be hard to suggest decent improvements, because we don't have any reason to believe that line 4 of  $F[0].xml must always be the place where your new  <keywords> $F[1] </keywords> string should properly replace the original line content.

    But a few things that would simplify your approach:

    • add "-l" to the perl options (perl -lane), and stop worrying about line-feed characters
    • read the whole input file into an array and close it
    • replace the fourth array element (index 3) with your new keyword stuff
    • open original file name again for output and write the array to it
    then hope you didn't just obliterate your xml data, given that you haven't done any error checking, XML parsing, yadda yadda...