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()"?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.