4

关于重载字符串化以及它如何与 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";
4

1 回答 1

5

重载的字符串化可以在每次调用时返回不同的字符串,因此您试图找到一个甚至还不存在的字符串的存储格式。当您对对象进行字符串化时,引用的 UTF8 标志会更新以反映字符串化对象的 UTF8。

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

于 2013-04-30T10:48:46.937 回答