我想实现我自己的
tweet compressor.基本上这会做到以下几点.但是我遇到了一些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/."\..,"."
我究竟做错了什么?
解决方法
两个问题.
首先,源代码中包含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/,'\. ',/; $tweet =~ s/$orig[$_]/$new[$_]/g for 0 .. $#orig; return $tweet; }