Skip to content

Instantly share code, notes, and snippets.

@xtetsuji
Created August 26, 2018 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xtetsuji/c21f725ee25f8741a9217e049292fe63 to your computer and use it in GitHub Desktop.
Save xtetsuji/c21f725ee25f8741a9217e049292fe63 to your computer and use it in GitHub Desktop.
Japanese zipcode serarch by KEN_ALL.CSV plain text. It is written at Perl-Entrance in Tokyo, 2018/08/25 for entertainment live coding show.
#!/usr/bin/env perl
use strict;
use warnings;
use utf8; # このスクリプトは UTF-8 で書かれている、文字列リテラルはそういう文字として評価する
use Encode qw(encode decode);
binmode STDOUT, ':utf8';
# https://www.post.japanpost.jp/zipcode/dl/kogaki-zip.html
my $file = 'KEN_ALL.CSV';
# 第1引数から検索キーワードをもらう。ターミナルの設定が UTF-8 だとしている
my $keyword = decode('utf-8', shift @ARGV);
# 与えられた検索キーワードを全角カタカナと半角数字に寄せて正規化
$keyword =~ tr/ぁ-ん/ァ-ン/;
$keyword =~ tr/0-9/0-9/;
$keyword =~ s/-//g;
print "keyword is $keyword\n";
if ( !-f $file ) {
die "ファイルがなかった\n";
}
# KEN_ALL.CSV は Shift_JIS 文字コードなので、それを変換しながら取り出す
open my $fh, '<:encoding(shift-jis)', $file or die;
while (my $line = <$fh>) {
chomp $line;
# iso-2022-jp には「半角カナ」が無いので、
# 文字コード変換を繰り返して iso-2022 を経由すれば半角カナが無くなるというバッドハック
# ちなみにここの処理がかなり遅いっぽい
# あと $keyword から /$keyword/ している部分も遅いはず
$line = decode('iso-2022-jp', encode('iso-2022-jp', $line));
if ( $line =~ /$keyword/ ) {
my @lines = split /,/, $line;
# とりあえず分割する実験なので、ラベルは付けない
for my $string (@lines) {
print ">>> $string\n";
}
#print "$line\n";
}
}
close $fh;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment