Here is one approach. It is not particularly elegent, but it gets the job done.
#!/user/bin/perl my $in_str = "[DATA]\n" . "data1\n" . "[ENTRY]\n" . "entrying here\n" . "[STORY]\n" . "story1\n"; my $out_str; print "\n"; print "IN STRING:\n"; print "$in_str"; print "\n"; my @decomposed = split("\n",$in_str); print "\n"; print "DECOMPOSED STRING:\n"; print join(", ",@decomposed); print "\n"; print "\n"; my @recomposed; my $start; my $stop; my $out_token; foreach my $token (@decomposed) { if($token =~ /\[(\w+)\]/){ $start = "<$1>"; $stop = "</$1>"; } else { $out_token = "$start"."$token"."$stop\n"; push(@recomposed, $out_token); } } $out_str = join("",@recomposed); print "\n"; print "OUT STRING:\n"; print "$out_str"; print "\n"; exit(0);
I presume that you're getting the data through some input stream (file reads or something similar). Note that in the above code I have not modeled that. Instead I set up a simple string variable $in_str to duplicate the specific input that you specified. That part of the challenge is up to you to work out. But the heart of the code below should take care of the conversion for you.
Note also that I have put in several print statements so that you can see what's going on along the way and to confirm that the code, in execution, is progressing properly. You, obviously, wouldn't need them in your code (though they represent a strategy to help be sure that an algorithm is behaving the way one expects/desires).
The other responders offer very good and sage advice and it would behoove you to head their suggestions and advice. Also, as throughout Perl, TMTOWDI; my approach is neither elegent nor, by any means, the only way to get the job done.
In reply to Re: convert to XML
by ack
in thread convert to XML
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |