基于Unicode的';tweet压缩器&x27;在Perl中

基于Unicode的';tweet压缩器&x27;在Perl中,perl,unicode,Perl,Unicode,我想实现我自己的。基本上,这样做如下。但是,我仍然遇到一些unicode问题 这是我的剧本: #!/usr/bin/env perl use warnings; use strict; print tweet_compress('cc ms ns ps in ls fi fl ffl ffi iv ix vi oy ii xi nj/, "\. " ,", "'),"\n"; sub tweet_compress { my $tweet = shift; $tweet =~

我想实现我自己的。基本上,这样做如下。但是,我仍然遇到一些unicode问题

这是我的剧本:

#!/usr/bin/env perl
use warnings;
use strict;

print tweet_compress('cc ms ns ps in ls fi fl ffl ffi iv ix vi oy ii xi nj/, "\. " ,", "'),"\n";

sub tweet_compress {
    my $tweet = shift;
    $tweet =~ s/\. ?$//;
    my @orig = ( qw/cc ms ns ps in ls fi fl ffl ffi iv ix vi oy ii xi nj/, ". " ,", ");
    my @new = qw/㏄ ㎳ ㎱ ㎰ ㏌ ʪ fi fl ffl ffi ⅳ ⅸ ⅵ ѹ ⅱ ⅺ nj . ,/;
    $tweet =~ s/$orig[$_]/$new[$_]/g for 0 .. $#orig;
    return $tweet;
}
但这会在终端打印垃圾:

?.?.?.?.?.?.?.f.?.f?.?.?.?.?.?.?.nj/."\..,"."

我做错了什么?

告诉
perl
你遇到了
使用utf8
两个问题

首先,在源代码中有unicode字符。确保将文件保存为utf8并使用use utf8 pragma


此外,如果您打算从控制台运行此程序,请确保它可以处理unicode。Windows命令提示符不能也将始终显示?无论您的数据是否正确。我在Mac OS上运行了这个,终端设置为处理utf8

其次,如果您的原始列表中有“.”,它将被解释为“任何单个字符”,并给出错误的结果-因此您需要在正则表达式中使用它之前对其进行转义。我对程序做了一些修改,使它能正常工作

#!/usr/bin/env perl
use warnings;
use strict;
use utf8; #use character semantics

#make sure the data is re-encoded to utf8 when output to terminal
binmode STDOUT, ':utf8';

print tweet_compress('cc ms ns ps in ls fi fl ffl ffi iv ix vi oy ii xi nj/, "\. " ,", "'),"\n";

sub tweet_compress {
    my $tweet = shift;
    $tweet =~ s/\. ?$//;
    my @orig = ( qw/cc ms ns ps in ls fi fl ffl ffi iv ix vi oy ii xi nj/, '\. ' ,", ");
    my @new = qw/㏄ ㎳ ㎱ ㎰ ㏌ ʪ fi fl ffl ffi ⅳ ⅸ ⅵ ѹ ⅱ ⅺ nj . ,/;
    $tweet =~ s/$orig[$_]/$new[$_]/g for 0 .. $#orig;
    return $tweet;
}

畏缩这是什么对Unicode的滥用?同意。卑鄙的黑客:)。此外,如果您打算存储它,它实际上会占用更多的空间,因为许多字符在utf8中占用3个字节。e、 g.cc需要2个字节,但是㏄ 将是3个字节0xE3 0x8F 0x84。更不用说tweet会在很多手机上中断(我们中的一些人使用短信获取tweet)。重点是,utf8标志符被计算为twitter的字符,因此根据tweet中的特殊字符数,它可以增加带宽。中文或日文140字比英文140字多得多;)您在
binmode
行中出现了一个错误--看起来像是先前编辑时留下的“控制台”一词。不要手动转义
@orig
中的内容,只需使用
quotemeta
(或
s///code>中的
\Q
):)“Windows命令提示符不能也将始终显示?不管你的数据是否正确。”-取决于代码页。我在这里是在utf8的上下文中说的,因为这就是本例中数据的存储方式。此外,我怀疑是否有一个单独的代码页可以覆盖我们在这里拥有的所有字符。有一种方法可以引导它使用chcp等()来显示utf8但是,这是一个很滑的斜坡,你永远无法确定到底是控制台还是你的代码。最好将控制台从等式中完全排除。霍布斯说了什么。这句话:$tweet=~s/$orig[$\u]/$new[$\u]/g代表0..$\u35; orig;应该是$tweet=~s/\Q$orig[$\u'\ E/$new[$\u]/g表示0..$#orig;,不必费心转义任何原始字符串