How can I write XML data to a file with Perl?

2019-07-23 11:39发布

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

标签: xml perl
8条回答
Explosion°爆炸
2楼-- · 2019-07-23 12:22

Several additional points of advice:

查看更多
时光不老,我们不散
3楼-- · 2019-07-23 12:25

If you want to write UTF-8 data to a file (as you say in your XML declaration, open the file with a UTF-8 encoding:

open my($fh), '>:utf8', 'data.xml' or die "Could not open file: $!";

print $fh qq{<?xml version="1.0" encoding="UTF-8">\n};
查看更多
登录 后发表回答