gpt4 book ai didi

perl - 重载字符串化和 utf8 标志

转载 作者:行者123 更新时间:2023-12-05 01:08:58 25 4
gpt4 key购买 nike

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

最佳答案

重载字符串化每次调用时都可能返回不同的字符串,因此您正在尝试查找甚至不存在的字符串的存储格式。当您对对象进行字符串化时,引用的 UTF8 标志会更新以反射(reflect)字符串化对象的 UTF8。
"".$t也适用于您使用的地方 say $t; .

关于perl - 重载字符串化和 utf8 标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16297754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com