【问题标题】:Uppercase accented characters in perlperl中的大写重音字符
【发布时间】:2012-11-07 00:23:00
【问题描述】:

有没有办法在perl中将重音字符大写,

my $string = "éléphant";

print uc($string);

所以它实际上打印了 ÉLÉPHANT ?

我的 perl 脚本以 ISO-8859-1 编码,$string 以相同编码打印在 xml 文件中。

【问题讨论】:

  • 刚刚运行了这个单行代码(使用 UTF-8),它按预期工作:perl -Mutf8 -E'binmode STDOUT, ":utf8"; say uc "éléphant"' use utf8 告诉 perl 源代码不是 ASCII,而是 Unicode。

标签: perl uppercase


【解决方案1】:

perl只懂US-ASCII和UTF-8,后者需要

use utf8;

如果要将文件保留为iso-8859-1,则需要显式解码文本。

use open ':std', ':encoding(locale)';
use Encode qw( decode );

# Source is encoded using iso-8859-1, so we need to decode ourselves.
my $string = decode("iso-8859-1", "éléphant");
print uc($string);

但最好将脚本转换为 UTF-8。

use utf8;  # Source is encoded using UTF-8
use open ':std', ':encoding(locale)';

my $string = "éléphant";
print uc($string);

如果您要打印到文件,请确保在打开文件时使用:encoding(iso-8859-1)(无论您使用哪种替代方法)。

【讨论】:

  • 好的,我意识到我可能遗漏了重要的一点。 $string 实际上是使用 CGI 包调用的参数的结果。我的 $string = param('word1');所以我实际上可能不得不在 ISO-8859-1 中编码 $string
  • 然后使用方法1。无论您使用哪种方法,在写入 XML 时都必须进行编码。 (我在底部提到了这一点。)总是解码输入,总是编码输出。
  • 谢谢,@ikegami:我不知道为什么,但是当我使用“使用打开”行时,我收到错误“无法通过包“TMInput”定位对象方法“BINMODE”。但是,它仅在使用时有效:code use utf8; use Encode qw(decode); my $word1 = decode("iso-8859-1", param('word1')); print uc($word1); code
  • 在 cpan 或 google 上没有提及 TMInput。不知道你做了什么。
  • 因为这是 latin1 特定的,它会在 99% 的 UTF-8 字符上失败。
【解决方案2】:

尝试这样做:

use Encode qw/encode decode/;

my $enc = 'utf-8'; # This script is stored as UTF-8
my $str = "éléphant\n";

my $text_str = decode($enc, $str);
$text_str = uc $text_str;
print encode($enc, $text_str);

输出

ÉLÉPHANT

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2020-03-08
    • 2011-10-02
    相关资源
    最近更新 更多