You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Perl中print语句出现Wide character error,如何解决该问题?

修复Perl的Wide character in print错误

这个错误的核心原因是:你已经将输入解码为Unicode字符串(宽字符),但输出句柄WRITE没有指定编码格式,Perl无法自动将宽字符转换为字节流输出。

以下是几种可行的修复方案:

方案1:打开输出句柄时指定编码

在打开WRITE句柄时,直接通过:encoding(utf-8)指定输出编码,这是最规范的做法:

# 替换原来的open语句
open my $WRITE, '>:encoding(utf-8)', 'output_file.txt' or die "无法打开输出文件: $!";

while (defined(my $i = <READ>)) {
    my $text_str = decode('utf-8', $i);
    $text_str =~ s/\xA7/§/g;
    $text_str =~ s/\t/\n/g;
    print $WRITE $text_str;
}

方案2:对已打开的句柄设置编码

如果无法修改打开句柄的代码,可以在输出前用binmode给WRITE句柄指定编码:

# 在循环前添加这行
binmode WRITE, ':encoding(utf-8)';

while (defined(my $i = <READ>)) {
    my $text_str = decode('utf-8', $i);
    $text_str =~ s/\xA7/§/g;
    $text_str =~ s/\t/\n/g;
    print WRITE $text_str;
}

补充说明

  • 脚本开头建议添加use utf8;,确保Perl能正确识别代码中直接写的Unicode字符(比如你代码里的§)。
  • 输入句柄READ也建议在打开时指定编码,替代手动调用decode,比如:open my $READ, '<:encoding(utf-8)', 'input_file.txt' or die $!;,这样读取时会自动解码,无需手动调用decode('utf-8', $i)。

内容的提问来源于stack exchange,提问作者Sai Pradyumna Tumma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:15:54