【问题标题】:perl output - failing in printing utf8 text files correctlyperl 输出 - 无法正确打印 utf8 文本文件
【发布时间】:2016-05-01 09:09:38
【问题描述】:

所以我有 utf8 文本文件,我想读入,将行放入数组中,然后打印出来。但是输出没有正确打印符号,例如输出行如下所示:

“arnÅ¿tein gehört gräflichen”

所以我尝试通过一行测试脚本,直接粘贴到 perl 脚本中,而不是从文件中读取它。那里的输出非常好。我检查了文件,它们是 utf8 unicode。文件仍然必须导致输出问题(?)。

因为脚本太长,我只是把它剪成相关的: (进入目录,打开文件,将输入引导到函数&align,分析它,将其添加到数组中,打印数组)

#!/usr/bin/perl -w
use strict;

use utf8;
binmode(STDIN,":utf8");
binmode(STDOUT,":utf8");
binmode(STDERR,":utf8");

#opens directory
#opens file from directory
 if (-d "$dir/$first"){
  opendir (UDIR, "$dir/$first") or die "could not open: $!";
  foreach my $t (readdir(UDIR)){
   next if $first eq ".";
   next if $first eq "..";

   open(GT,"$dir/$first/$t") or die "Could not open GT, $!";
   my $gt= <GT>;
   chomp $gt;

   #directly pasted lines in perl   - creates correct output
   &align("det man die Profeſſores der Philoſophie re- ");

    #lines from file    - output not correct
    #&align($gt);
    close GT;
    next;

  }closedir UDIR;
}

有什么想法吗?

【问题讨论】:

    标签: perl unicode utf-8 character-encoding file-handling


    【解决方案1】:

    您告诉 Perl 您的源代码是 UTF-8,而 STDIN、STDOUT 和 STDERR 是 UTF-8,但您没有说您正在读取的文件包含 UTF-8。

    open(GT,"<:utf8", "$dir/$first/$t") or die "Could not open GT, $!";
    

    如果不这样,Perl 假定文件是用 ISO-8859-1 编码的,因为如果你不指定其他字符集,那是 Perl 的默认字符集。它有助于将这些 ISO-8859-1 字符转码为 UTF-8 以进行输出,因为您已经告诉它 STDOUT 使用 UTF-8。由于该文件实际上是 UTF-8,而不是 ISO-8859-1,因此您会得到不正确的输出。

    【讨论】:

    • 谢谢,我认为“binmode”会在 utf8 上设置输入流,但显然没有:)
    • binmode 为您调用它的文件句柄设置 UTF-8。当您显式打开文件时,其编码与 STDIN 或 STDOUT 使用的内容无关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多