Help us understand the problem. What is going on with this article?

Perl の DBI で EUC_JP の MariaDB のデータを読み込んだ時の文字化け

文字コードを EUC_JP としたMariaDB から下記のプログラムを実行した時に文字化けをする問題です。

Ubuntu 20.04 で実行した場合は文字化けが発生しません。

mojibake_aa.png

Arch Linux, RaspberryPi では文字化けします。

mojibake_bb.png

city_read.pl
#! /usr/bin/perl
#
#   city_read.pl
#
#                   Jul/04/2020
#
# -----------------------------------------------------------------------
use strict;
use warnings;
use DBI;
#
# -----------------------------------------------------------------------
sub get_date_mod_proc
{
    my ($mday,$mon,$year) = (localtime (time))[3..5];
    $mon += 1;
    $year += 1900;
    my $date_mod = "$year-$mon-$mday";

    return $date_mod;
}

# -----------------------------------------------------------------------
print STDERR "*** city_read.pl *** start ***\n";
my $date_mod = get_date_mod_proc();
print STDERR $date_mod . "\n";
#
my $host = 'example.com';
my $constr='DBI:mysql:database=city:host=' . $host;
my $user = '******';
my $passwd = '******';
#
my $dbi=DBI->connect($constr, $user, $passwd);

my $sql = "select distinct Name from cities";
my $sth = $dbi->prepare($sql);
$sth->execute;
my $num_rows = $sth->rows;


print "Content-Type: text/html\n\n";

print "<!DOCTYPE html>\n";
print "<html lang=\"ja\">\n";
print "<head>\n";
print "<meta http-equiv=\"CONTENT-TYPE\" content=\"text/html; charset=EUC-JP\" />\n";
print "<title>mariadb_read.pl</title>\n";
print "</head>\n";
print "<body>\n";

print "*** city_read.pl *** start ***<br />\n";
print $date_mod . "<br />\n";
print $host . "<p />\n";
print "num_rows =" . $num_rows . "<p />\n";

for (my $it=0; $it<$num_rows; $it++)
    {
    my @aa = $sth->fetchrow_array;
    my $pp = $aa[0];
    print "$pp<br />\n";
    }

print "<p />";
print "*** Jul/04/2020 ***<p />\n";
print "*** end ***<p />\n";
print "</body>\n";
print "</html>\n";
#
my $rc = $sth->finish();
$dbi->disconnect();
#
print STDERR "*** city_read.pl *** end ***\n";
# -----------------------------------------------------------------------

Arch と RaspberryPi で文字化けしないようにするには、connect 後に次のコードを入れます。

my $dbi=DBI->connect($constr, $user, $passwd);
$dbi->prepare("SET NAMES ujis")->execute;
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away