in reply to Re^2: Writing to a file
in thread Writing to a file
In order to understand why the output to sourcetag1.xml is the way that it is - why the <HEADLINE> tag is repeated three times - you must carefully read and understand the program and follow what it does, step by step, to produce the output.
Here is a version of your program with some extra print statements. If you study the output carefully you should be able to follow the execution of the program. This will show you why the <HEADLINE> tag surrounds each of the last three lines.
use strict; use warnings; my $fh; my $tag; while(<DATA>){ print "\nNext iteration of while loop\n"; print "\$tag = $tag\n"; print "\$_ = $_"; chomp $_; $_ =~ s/[\cA-\cZ]//g; #$_ =~ s/^\s+$//g; #$_ =~ s/\n//g; #$_=~ s/[\r]//gs; if(/^{(.*)}/) { print "\tThis line is a tag line\n"; $tag = $1; print "\t\$tag has been set to $tag\n";; } else { print "\tThis line is not a tag line.\n"; if($tag eq 'FILE') { print "\t\t\$tag is equal to 'FILE', so this line gives a +new filename\n"; my $filename = $_; # print "The filename is $filename\n"; open($fh, '>', "$filename.xml") or die "$filename: $!"; print $fh '<?xml version="1.0"?>',"\n"; print $fh "<root>\n"; print $fh "<FILE>$filename</FILE>"; print "\t\tAny previously open output file has been closed +\n"; print "\t\tand new output file $filename has been opened.\ +n"; print "\t\tand some initial text has been written to it.\n +"; } elsif(defined($fh)) { print "\t\t\$tag is not equal to 'FILE' and we have an ope +n output file.\n"; if( $_ ne ''){ #### Remove the blnak lines print "\t\t\tand the line is not blank\n"; print "\t\t\tso, write it to the output file\n"; print "\t\t\tas '<$tag>$_</$tag>'\n"; chomp $_; print $fh "<$tag>$_</$tag>\n"; } #print $fh "</root>"; } } } close($fh); exit(0); __DATA__ ^B^B^B^B^B^B {FILE} sourcetag1 {NUMBER} 00000 {SOURCE} source1 {KEYWORD} {AUTHOR} author1 staff1 {HEADLINE} DISPOSABLE DECOR: THE CUTTING EDGE DULLS FAST\ STYLE AT A SPEED USUALLY ASSOCIATED WITH WARDROBE ITEMS. {FILE} sourcetag2 {NUMBER} 00002 {SOURCE} sourcenam2 {KEYWORD} {AUTHOR} author2 staff2
An alternative to adding print statements to you program is to use the debugger (see perldebug). With the debugger you can execute your program one statement at a time, examine and even change variables as it executes. In the beginning it may be easier to use print statements, but the debugger is a very powerful tool that can be very easy and helpful if you take the time to learn how to use it.
|
|---|