Uppercase accented characters in perl

故事扮演 提交于 2019-12-10 20:41:39

问题


Is there a way to uppercase accented characters in perl,

my $string = "éléphant";

print uc($string);

So that it actually prints ÉLÉPHANT ?

My perl script is encoded in ISO-8859-1 and $string is printed in an xml file with the same encoding.


回答1:


perl only understands US-ASCII and UTF-8, and the latter requires

use utf8;

If you want to keep the file as iso-8859-1, you'll need to decode the text explicitly.

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);

But it's probably better to convert the script to UTF-8.

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

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

If you're printing to a file, make sure you use :encoding(iso-8859-1) when you open the file (no matter which alternative you use).




回答2:


Try doing this :

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);

OUTPUT :

ÉLÉPHANT


来源:https://stackoverflow.com/questions/13261522/uppercase-accented-characters-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!