Perl中基于Unicode的"tweet压缩器"

sin*_*ish 3 unicode perl

我想实现自己的推文压缩器.基本上这会做到以下几点.但是我遇到了一些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/? ? ? ? ? ? ? fl ? ? ? ? ? ? ? ? ? ? ?/;
    $tweet =~ s/$orig[$_]/$new[$_]/g for 0 .. $#orig;
    return $tweet;
}
Run Code Online (Sandbox Code Playgroud)

但是这会在终端打印垃圾:

??????????????f???f???????????????/?"\??,"?"
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

dee*_*akg 6

两个问题.

首先,源代码中包含unicode字符.确保将文件保存为utf8 使用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/? ? ? ? ? ? ? fl ? ? ? ? ? ? ? ? ? ? ?/;
    $tweet =~ s/$orig[$_]/$new[$_]/g for 0 .. $#orig;
    return $tweet;
}
Run Code Online (Sandbox Code Playgroud)