2010-08-22 39 views

Trả lời

13

unpack sẽ hiệu quả hơn splitord, bởi vì nó không phải thực hiện một loạt các chuỗi 1 ký tự tạm thời:

use utf8; 

my $str = '中國c'; # Chinese language of china 

my @codepoints = unpack 'U*', $str; 

print join(',', @codepoints) . "\n"; # prints 20013,22283,99 

Một điểm chuẩn nhanh chóng cho thấy nó nhanh hơn split+ord khoảng 3 lần:

use utf8; 
use Benchmark 'cmpthese'; 

my $str = '中國中國中國中國中國中國中國中國中國中國中國中國中國中國c'; 

cmpthese(0, { 
    'unpack'  => sub { my @codepoints = unpack 'U*', $str; }, 
    'split-map' => sub { my @codepoints = map { ord } split //, $str }, 
    'split-for' => sub { my @cp; for my $c (split(//, $str)) { push @cp, ord($c) } }, 
    'split-for2' => sub { my $cp; for my $c (split(//, $str)) { $cp = ord($c) } }, 
}); 

Kết quả:

   Rate split-map split-for split-for2  unpack 
split-map 85423/s   --  -7%  -32%  -67% 
split-for 91950/s   8%   --  -27%  -64% 
split-for2 125550/s  47%  37%   --  -51% 
unpack  256941/s  201%  179%  105%   -- 

Sự khác biệt là ít rõ rệt với chuỗi ngắn hơn, nhưng unpack vẫn nhanh hơn gấp hai lần. (split-for2 là nhanh hơn so với chia rẽ khác một chút vì nó không xây dựng một danh sách các codepoints.)

3

Xem perldoc -f ord:

foreach my $c (split(//, $str)) 
{ 
    print ord($c), "\n"; 
} 

Hoặc nén vào một một dòng: my @chars = map { ord } split //, $str;

Data::Dumper ed, điều này tạo ra:

$VAR1 = [ 
      20013, 
      22283, 
      99 
     ]; 
3

Để có utf8 trong mã nguồn của bạn công nhận là như vậy, bạn phải use utf8; trước:

$ perl 
use utf8; 
my $str = '中國c'; # Chinese language of china 
foreach my $c (split(//, $str)) 
{ 
    print ord($c), "\n"; 
} 
__END__ 
20013 
22283 
99 

hoặc ngắn gọn hơn,

print join ',', map ord, split //, $str; 
2

http://www.perl.com/pub/2012/04/perlunicook-standard-preamble.html

#!/usr/bin/env perl 


use utf8;  # so literals and identifiers can be in UTF-8 
use v5.12;  # or later to get "unicode_strings" feature 
use strict; # quote strings, declare variables 
use warnings; # on by default 
use warnings qw(FATAL utf8); # fatalize encoding glitches 
use open  qw(:std :utf8); # undeclared streams in UTF-8 
# use charnames qw(:full :short); # unneeded in v5.16 

# http://perldoc.perl.org/functions/sprintf.html 
# vector flag 
# This flag tells Perl to interpret the supplied string as a vector of integers, one for each character in the string. 

my $str = '中國c'; 

printf "%*vd\n", ",", $str; 
Các vấn đề liên quan