Could you please correct my code below.
#!/usr/local/bin/perl
open (MYFILE, '>>data.xml');
print MYFILE "<?xml version="1.0" encoding="UTF-8"?>\n";
close (MYFILE);
Updated.
#!/usr/local/bin/perl
open (MYFILE, '>>data.xml');
print MYFILE '<?xml version="1.0" encoding="UTF-8"?\>'."\n";
print MYFILE '<?xml version="1.0" encoding="UTF-16"?\>'."\n";
close (MYFILE);
output: working well now.
<?xml version="1.0" encoding="UTF-8"?\>
<?xml version="1.0" encoding="UTF-16"?\>
BUT.
#!/usr/local/bin/perl
open (MYFILE, '>>data.xml');
print MYFILE '<?xml version="1.0" encoding="UTF-8"?\>'.'\n';
print MYFILE '<?xml version="1.0" encoding="UTF-16"?\>'.'\n';
close (MYFILE);
Output: # error format with \n
<?xml version="1.0" encoding="UTF-8"?\>\n<?xml version="1.0" encoding="UTF-16"?\>\n
The problem is you have unescaped quotes in the string. Either escape the quotes using the backslash or surround your print string with qq{}:
Your problem is that you had nested double quotes; using
qq{}
to delimit the string will solve this issue.I would recommend to use:
Always turn on warnings and strictures, so you find out earlier what went wrong, and get more details why:
Always use the lexical-variabled, three-argument form of
open
(there's a big discussion why over here), and always check the return value (it will return an error if something went wrong, and put the reason why in the$!
variable (see under$!
at perldoc perlvar). Also,die
will print the line number of where the program quit if you don't end your string with a\n
(more at perldoc -f die).And use double-quotes around the
\n
so that it is printed properly:Always, always, ALWAYS check the value returned from
open
, e.g.,Note the important bits in the error message:
$0
open
$!
Without a newline at the end of the string passed to
die
, it appends the file and line number where your program died.Here is some code of mine for printing an XML file: