# ユニークキー作成スクリプト
# by take-ash
# 2013.06.07
#
# 重複のないランダムなキーの一群を作る。
use strict;
use warnings;
use utf8;
use Encode;
use Text::CSV_XS;
use Win32::Unicode::Native;
my $charsetFile = 'UTF-8';
my $fileNameOut = 'uniqueKeys.txt'; # 出力ファイル名。
my $keyLength = 6; # キーの長さ
my $keyMax = 50; # キーの個数
my $possibleChar = # 使用可能文字
# 'あいうえお' .
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .
'abcdefghijklmnopqrstuvwxyz' .
'0123456789';
my $keyCharMax = length( $possibleChar );
if ( ( $keyCharMax ** $keyLength ) < $keyMax ){
die( "Too short KeyLength or Too few PossibleChar against KeyMax.\n" );
}
my %keyPool = ();
my @keyList = ( [ 'ID', 'Key' ] );
srand( time );
$| = 1;
for( my $i=1; $i <= $keyMax; ++$i ){
printf( "%d/%d\r", $i, $keyMax );
my $tmpKey = makeNewKey();
while( $keyPool{ $tmpKey } ){
$tmpKey = makeNewKey();
}
$keyPool{ $tmpKey } = 1;
push( @keyList, [ $i, $tmpKey ] );
}
print "\n";
$| = 0;
my $csv = Text::CSV_XS->new({ binary => 1, sep_char => "\t", eol => $/ });
open( my $OUT, ">:encoding($charsetFile)", $fileNameOut )
or die( "$fileNameOut: $!\n" );
foreach my $row ( @keyList ){
$csv->print( $OUT, $row );
}
close( $OUT );
exit;
sub makeNewKey {
my $result = '';
while( length( $result ) < $keyLength ){
$result .= substr( $possibleChar, int( rand( $keyCharMax ) ), 1 );
}
return $result;
}
# EOF