2013-04-30 92 views
4

有一些我不明白重載字符串化以及它如何與utf8標誌交互。重載字符串化和utf8標誌

例如下面的代碼打印:

n is utf8 at ./test_stringify_utf8.pl line 46. 
$t->{name} is utf8 at ./test_stringify_utf8.pl line 47. 
t is not utf8 at ./test_stringify_utf8.pl line 48. 
Derviş 
t is utf8 at ./test_stringify_utf8.pl line 50. 

如果我刪除say $t,輸出的最後一行也將是t is not utf8

#!/usr/bin/env perl 

use utf8; 
use Encode qw/is_utf8/; 
use strict; 

use Modern::Perl '2013'; 

package Test; 
use strict; 

sub new { 
    my ($class, $name) = @_; 

    my $self = { name => $name }; 
    bless $self, $class; 

    return $self; 
} 

BEGIN { 
    my %OVERLOADS = (fallback => 1); 

    $OVERLOADS{'""'} = 'to_string'; 

    use overload; 
    overload->import(%OVERLOADS); 
} 

sub to_string { shift->{name} } 


package main; 

my $n = "Derviş"; 
my $t = Test->new($n); 

binmode STDOUT, ":utf8"; 

is_utf8($n)   ? warn "n is utf8"   : warn "n is not utf8"; 
is_utf8($t->{name}) ? warn '$t->{name} is utf8' : warn '$t->{name} is not utf8'; 
is_utf8($t)   ? warn "t is utf8"   : warn "t is not utf8"; 
say $t; 
is_utf8($t) ? warn "t is utf8" : warn "t is not utf8"; 

回答

5

重載字串可以在每次它被稱爲時間返回不同的字符串,所以你試圖找到一個甚至不存在的字符串的存儲格式。在對對象進行字符串化時,引用的UTF8標誌將更新以反映字符串化對象的UTF8。

"".$t也可以在你使用的地方使用say $t;

+0

替換了我的答案。 – ikegami 2013-04-30 11:11:17