data.txt
\xB6\xD7\xB3\xF8 \xB7\x4A\xB3\xF8
\xB6\xD7\xBD\x73 \xB7\x4A\xBD\x73
\xB6\xD7\xA5\x5A \xB7\x4A\xA5\x5A
\xB6\xD7\xB6\xB0 \xB7\x4A\xB6\xB0
\xB4\xE5\xBF\xB3 \xB9\x43\xBF\xB3
\xB4\xE5\xBE\xC7 \xB9\x43\xBE\xC7
\xAA\xED\xB5\xFD \xAA\xED\xC3\xD2
\xBF\xEB\xB5\xFD \xBF\xEB\xC3\xD2
\xC5\x47\xB5\xFD \xC5\x47\xC3\xD2
以 tab 分離,前面的是 key 也就是需要轉換的 pattern 後面是 value 也就是需要轉換成的文字。
a.pl
將文字檔轉換成一個 dbfile (data.db) 也就是說將程式與資料分開。你可以將資料存在另外一個文字檔,一方面增加資料的時候不必去修改程式另一方面可以縮小程式。
轉換文字檔成資料庫(data.db)只需要作一次,如果 data.txt 沒有異動不需要重做這個轉換。此外這個資料庫是一個排序過的資料庫,搜尋時間應該會縮短。
#!/usr/bin/perl
#use warnings;
#use strict;
use DB_File;
$DB_BTREE->{'compare'} = sub {
my ($key1, $key2) = @_;
"\L$key1" cmp "\L$key2";
};
# Declaration
our (%hash, $key, $value);
my $DB_FILE = "data.db";
my $DATAFILE = "data.txt";
my %hash;
my $line;
# delete $DB_FILE
unlink $DB_FILE ;
#
open(DATA, $DATAFILE);
tie(%hash, "DB_File", $DB_FILE, O_RDWR|O_CREAT, 0666, $DB_BTREE)
or die "Cannot open DB_FILE $DB_FILE : $!\n";
print "Before Sort \n\n";
while($line = <DATA>)
{
chomp($line);
($key, $value) = split(/\t/, $line);
print $key, " -> ", $value, "\n";
$hash{$key} = $value;
}
print "\nAfter Sort\n\n";
while(my($key, $value) = each %hash)
{
print $key, " -> ", $value, "\n";
}
# close file
untie % hash;
close DATA;
從 dbfile 比對 c.pl
#!/usr/bin/perl
use warnings;
use strict;
use DB_File;
our (%hash, $key, $value);
my $DB_FILE = "data.db";
tie(%hash, "DB_File", $DB_FILE, O_RDWR, 0666, $DB_BTREE)
or die "Cannot open file '$DB_FILE' $!\n";
$key = $ARGV[0];
print $key,"\n";
$value = $hash{$key};
print $value, "\n";
untie %hash;
例如 ./c.pl "\xB6\xD7\xBD\x73" 會回應
\xB6\xD7\xBD\x73
\xB7\x4A\xBD\x73
這是一個資料庫查詢的範例,使用時要比較快的話要把螢幕輸出,如 print 之類的指令關掉。
所以你的程式在比對的時候可以改成去查詢資料庫,如果有傳回值就可以執行轉換這個傳回值。要是沒有就可以 return,這樣的話就可以只比對一次就可以。
詳情可以找 perl DB_File 的文章