gpt4 book ai didi

perl - 打印带有特殊字符的变量时如何禁用字符串插值?

转载 作者:行者123 更新时间:2023-12-02 06:02:10 24 4
gpt4 key购买 nike

在 Perl 中,我使用 XML::Twig 读取 XML 文件。一些属性的文本如下所示:

<p>Here is some text.</p>

<p>Some more text.

我正在将此属性读入名为 $Body 的变量中。我想将这个变量打印到一个文件中而不插入字符串中的特殊字符,即输出应该看起来与输入完全一样。我的代码如下所示:

open (my $OUT, ">", "out.csv") or die $!;
print $OUT $Body;

但是,当我查看 out.csv 时,我看到:

<p>Here is some text.</p>

<p>Some more text.

相反,我想查看原始字符串:

&lt;p&gt;Here is some text.&lt;/p&gt;&#xA&;#xA;&lt;p&gt;Some more text.

我尝试了以下但没有成功:

  • print $OUT '$Body'; 不起作用,只显示“$Body”
  • print $OUT "$Body"; 不起作用,与没有引号一样。
  • print $OUT qw{$Body}; 不起作用,只显示“$Body”。

    这是一个完整的例子:

tmp.xml

<?xml version="1.0" encoding="utf-8"?>
<root>
<node Body="&lt;p&gt;Here is some text.&lt;/p&gt;&#xA;&#xA;&lt;p&gt;Some more text."/>
</root>

代码:

#!/usr/bin/perl
use strict;
use XML::Twig;

my $t=XML::Twig->new();
$t->parsefile("tmp.xml");

my $root= $t->root;

open (my $OUT, ">", "out.csv") or die();

my @nodes = $root->children('node'); # get the para children
foreach my $node (@nodes){
my $Body = $node->{'att'}->{'Body'};
print $OUT $Body;
}

结果:

[dev@mogli:/swta] $ ./script.pl 
[dev@mogli:/swta] $ cat out.csv
<p>Here is some text.</p>

<p>Some more text.

最佳答案

XML::Twig 正在执行反编码。将 keep_encoding 标志传递给它以防止出现这种情况:

my $t = XML::Twig->new(keep_encoding => 1);

关于perl - 打印带有特殊字符的变量时如何禁用字符串插值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18960655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com