开发者

How can I use the range operator '..' to create a utf-8 alphabet?

开发者 https://www.devze.com 2023-02-15 12:37 出处:网络
Is there a way to create a UTF-8 alphabet array using the Perl \'..\' operator? For example, this one won\'t work:

Is there a way to create a UTF-8 alphabet array using the Perl '..' operator?

For example, this one won't work:

$ cat t开发者_如何学C.pl
#!/usr/bin/perl

use Data::Dumper;
use encoding 'utf8';

print Dumper('А'..'Я'); # not working!
print Dumper('А','Б','В'); # ...works fine! but needs to be filling letter by letter

$ perl t.pl
$VAR1 = "\x{410}";
$VAR1 = "\x{410}";
$VAR2 = "\x{411}";
$VAR3 = "\x{412}";

$ echo $LANG
en_US.UTF-8

Any advice?


This is mentioned - briefly - in the range operator docs. You need to use the ord and chr functions:

#!/usr/bin/perl

use Data::Dumper;
use encoding 'utf8';

my @arry = map { chr } ord( 'А' ) .. ord( 'Я' );
for my $letter ( @arry ) {
    print "$letter ";
}
print "\n";

Output:

А Б В Г Д Е Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ъ Ы Ь Э Ю Я

The result you see arises because the initial value of the range isn't part of a 'magical' sequence (a non-empty string matching /^[a-zA-Z]*[0-9]*\z/), so the operator just returns that initial value.

0

精彩评论

暂无评论...
验证码 换一张
取 消