http://qs1969.pair.com?node_id=741738

brycen has asked for the wisdom of the Perl Monks concerning the following question:

So I just learned that if you have a LATIN1 string, and a UTF-8 string, and you join them, the result is utf8, and the LATIN1 is mangled:
#! /usr/bin/perl # Perl v5.8.8 use strict; use Data::Dumper; use Encode; my $string1 = "weight_\x{2639}"; # Valid Unicode my $string2 = "weight_\xc2"; # Valid iso-8859-1 my @words; push(@words,$string1); push(@words,$string2); my $str = join(",", @words); print STDERR "mangled : ".print_chrcodes($str)."\n"; my @words; Encode::_utf8_off($string1); push(@words,$string1); Encode::_utf8_off($string2); push(@words,$string2); my $str = join(",", @words); print STDERR "preserved: ".print_chrcodes($str)."\n"; ############################################################# sub print_chrcodes { my $str = shift; my $ret; foreach my $ascval (unpack("C*", $str)) { $ret .= chr($ascval) if($ascval < 128); $ret .= sprintf ("<#%x>",$ascval) if($ascval >= 128); } return $ret; }
# perl -v This is perl, v5.8.8 built for x86_64-linux-gnu-thread-multi # perl test.pl mangled : weight_<#e2><#98><#b9>,weight_<#c3><#82> preserved: weight_<#e2><#98><#b9>,weight_<#c2>

We have a DBI / DBI::Pg application that does "SET CLIENT ENCODING LATIN1", which has been running for years. A one point it comes up with a list of "unique" words, which have always had the rare duplicate. The DB results get split into words, some of which get Perl's magic utf8 flag, some not, triggering the above when joined again. The actual examples are valid sequences of LATIN1 that are also, viewed as bytes, valid utf8.

The question for the Monks is "should I call _utf8_off() on all strings coming from the database?". Is that fast, cheap, and will the utf8_off flag persist once the string is split and combined and processed through many levels of code? Will the application run notably faster on byte oriented strings? And what kind of unintended consequences might I face? See also http://www.perlmonks.org/?node_id=314423

And "is this a reportable bug in join()"?