我想将ABCDEF
转换为A,B,C,D,E,F
使用 Perl 执行此操作的最快方法是什么?
我有很多要转换的字符串,字符串最长可达32768字节。所以,我想降低字符串转换的开销。
答案 0 :(得分:8)
怎么样
$string =~ s/.\K(?=.)/,/g; # using \K keep escape
$string =~ s/(?<=.)(?=.)/,/g; # pure lookaround assertion
或者
$string = join ",", split(//, $string);
要找到最快的解决方案,请使用Benchmark
。
额外信用:
这是我尝试的基准测试的结果。令人惊讶的是,\K
转义比纯转换快得多,这与分割/连接一样快。
use strict;
use warnings;
use Benchmark qw(cmpthese);
my $string = "ABCDEF" x 1000;
cmpthese(-1, {
keep => 'my $s = $string; $s =~ s/.\K(?=.)/,/g',
lookaround => 'my $s = $string; $s =~ s/(?<=.)(?=.)/,/g',
splitjoin => 'my $s = $string; $s = join ",", split(//, $string)'
});
<强>输出:强>
Rate splitjoin lookaround keep
splitjoin 6546367/s -- -6% -47%
lookaround 6985568/s 7% -- -44%
keep 12392841/s 89% 77% --
答案 1 :(得分:2)
$ perl -le 'print join(",", unpack("(A)*", "hello"))'
h,e,l,l,o
$ perl -le 'print join(",", unpack("C*", "hello"))'
104,101,108,108,111
$ perl -le 'print join(",", unpack("(H2)*", "hello"))'
68,65,6c,6c,6f
答案 2 :(得分:1)
my $str = "ABCDEFGHIJKL";
my @chars = $str =~ /./sg;
print join ",", @chars;
答案 3 :(得分:1)
如果您正在尝试打印较低开销的字符串,您可能只想在解析字符串时打印字符串,而不是在内存中进行整个转换,即
while (m/(.)\B/gc){
print "$1,";
};
if (m/\G(.)/) {
print "$1\n";
}