perl5 の DBI モジュールを使用する際で
data_source の指定パスに日本語含まれてる場合に嵌った。
環境
- Windows 7, 10
- ActivePerl
>perl --version This is perl 5, version 22, subversion 1 (v5.22.1) built for MSWin32-x64-multi-t hread (with 1 registered patch, see perl -V for more detail) Copyright 1987-2015, Larry Wall Binary build 2201 [299574] provided by ActiveState http://www.ActiveState.com Built Jan 4 2016 12:12:58 Perl may be copied only under the terms of either the Artistic License or the GNU General Public License, which may be found in the Perl 5 source kit. Complete documentation for Perl, including FAQ lists, should be found on this system using "man perl" or "perldoc perl". If you have access to the Internet, point your browser at http://www.perl.org/, the Perl Home Page.
結論
connect する際に utf8 にエンコードするといける
アプローチがあってるかどうかは謎
良いアプローチあったら教えてください
テスト
#!/usr/bin/perl use strict; use warnings; use utf8; use Encode qw/encode decode/; use DBI; my $file_enc = "cp932"; binmode(STDIN,":encoding($file_enc)"); binmode(STDOUT,":encoding($file_enc)"); binmode(STDERR,":encoding($file_enc)"); my $db_loc = $ARGV[0]; my $data_source = "dbi:SQLite:$db_loc"; my $dbh = DBI->connect($data_source); $dbh->disconnect; print "できた";
結果
>perl test.pl ほんとやめて\test.db DBI connect('\x{0082}U\x{0082}n\x{0082}A\x{0082}a\x{0082}s\x{0082}A\test.db','', ...) failed: unable to open database file at test.pl line 21. Can't call method "disconnect" on an undefined value at test.pl line 23.
修正
#!/usr/bin/perl use strict; use warnings; use utf8; use Encode qw/encode decode/; use DBI; my $file_enc = "cp932"; binmode(STDIN,":encoding($file_enc)"); binmode(STDOUT,":encoding($file_enc)"); binmode(STDERR,":encoding($file_enc)"); my $db_loc = $ARGV[0]; my $utf8_db_loc = decode($file_enc, $db_loc); $utf8_db_loc = encode("utf8", $utf8_db_loc); my $data_source = "dbi:SQLite:$utf8_db_loc"; my $dbh = DBI->connect($data_source); $dbh->disconnect; print "できた";