Overload string and utf8 flag

Something I don’t understand about line overloading and how it interacts with utf8 flag.

For example, the following code prints:

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. 

If I delete say $t , the last line of output will also be 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
source share
1 answer

An overloaded string may return another string each time it is called, so you are trying to find a format for storing a string that does not yet exist. When you gate the object, the link UTF8 flag is updated to reflect the UTF8 string object.

"".$t will also work where you used say $t; .

+5
source

All Articles