Perl:从文件导入包含 ÅäÖ 的文本

标签 perl file encoding io

我最终想要实现的目标是将文件中的所有小写字符转换为大写字符并将它们写入终端。

use utf8;
binmode STDOUT, ":utf8";

$text = "ABCÅÄÖ\n";

$text =~ tr/A-Ö/a-ö/;
print $text;

输出:

abcåäö

正如预期的那样。

但是当我尝试从文件导入相同的文本时,它变得很疯狂。

use utf8;
binmode STDOUT, ":utf8";

open FILE, $filename or die "An error occurred while reading the file: $!";
$text = join '', <FILE>;
close FILE or die "An error occurred while closing the file: $!";

$text =~ tr/A-Ö/a-ö/;
print $text;

输出

ABCàñ

我假设导入的文本未正确编码。有人知道如何在导入时对文本进行编码吗?

提前致谢。

jack

最佳答案

您没有告诉 Perl 解码该文件。

use strict;
use warnings;

use utf8;                             # Source code is UTF-8.
use open ':std', ':encoding(UTF-8)';  # Terminal and files are UTF-8.

my $qfn = ...;

open(my $fh, '<', $qfn)
   or die("Can't open file $qfn: $!\n");

my $text = do { local $/; <$fh> };
print(lc($text));

关于Perl:从文件导入包含 ÅäÖ 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27107883/

相关文章:

ios - 在 iOS 应用程序上保存大文件

c++ - 如何正确初始化 std::set<std::string>?

perl - 无法使用 mojolicious 以 xml 形式发送 HTTP 响应

javascript - 从 Perl 发送 JSON 日期到 google charts API

c - 我的链表未填充 C

html - 在 XML 属性中转义特殊(HTML 标记)字符?

MySQL - 俄语字符显示不正确

php - PHP/MySQL 编码

c - 如何安全地将数据从 C 传输到 Perl?

perl - 如何解决警告 "Use of assignment to $[ is deprecated"?