in reply to Generating xml from Perl
You don't need to read the input file more than once. It looks like the OP is reading it twice -- once to count the lines and once to read the lines into an array. You could just read it into the array then use "scalar @array" to see how many lines it is.
You don't need to open the file for output more than once. The OP opens it once with ">", and then again with ">>" to add data to it. You could just print the extra data while it's open for output the first time.
You don't need to assign "abc.xml" to $file four times; but just in case things don't go the way you expect, it would be prudent to use a different file name when opening the file for output -- that way the original file is preserved.
As for what you're actually trying to do, I think you have some risk of it going quite wrong unless you are absolutely, perfectly confident about the origin and exact format of your xml data.
You read the original file line by line into an array, and replace the last array element (the last line) with the content of some other scalar ("$xml1") -- though your post doesn't give a clue about where this comes from, or what might have been on the last line of the original file.
Since xml is supposed to be agnostic (unconcerned, flexible, inattentive) about the distribution of line-termination characters between tags, your approach would break horribly if you get a stream with a pattern of line-breaks (or absence of them) that you don't expect.
So it makes more sense to be explicit about which particular tag(s) in the original file you need to replace, and use one of the XML parser modules to focus on replacing just that tag.
Having said all that, if you really are absolutely, perfectly confident about the input data, here's a shorter version of the OP code:
my $inp = "abc.xml"; my $out = "new_abc.xml"; # or maybe some more meaningful name... open( INP, $inp ) or die "$inp: $!" ); open( OUT, $out ) or die "$out: $!" ); my @array = <INP>; # read all input lines into @array # ... $xml_add has to come from somewhere ... $array[$#array] = $xml_add; # replace last line print OUT join "", @array;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Generating xml from Perl
by jonhy (Initiate) on May 10, 2005 at 03:59 UTC |