2

我想转换ABCDEFA,B,C,D,E,F

使用Perl最快的方法是什么?

我有很多字符串要转换,字符串最长可达 32768 字节。所以,我想降低字符串转换的开销。

4

4 回答 4

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%         --
于 2013-05-28T16:52:39.047 回答
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
于 2013-05-28T16:59:38.240 回答
1
my $str = "ABCDEFGHIJKL";

my @chars = $str =~ /./sg;

print join ",", @chars;
于 2013-05-28T16:58:49.837 回答
1

如果您尝试以较低的开销打印字符串,您可能只想在解析字符串时打印字符串,而不是在内存中进行整个转换,即

while (m/(.)\B/gc){
 print "$1,";
};
if (m/\G(.)/) {
  print "$1\n";
}
于 2013-05-28T17:08:14.550 回答