我的数据文件: votes.txt 由与以下内容相同的行组成:
VOTE 1168241980 Campaign:ssss_uk_01B Validity:during
Choice:Tupele CONN:MIG00VU MSISDN:00088866655598
GUID:A34-FDS87-FHDHDH-DHDHDHD0 Shortcode:63334
每个条目用空格分隔。我目前有 19 行的样本。
领域:
CONN:MIG00VU MSISDN:00088866655598
GUID:A34-FDS87-FHDHDH-DHDHDHD0 Shortcode:63334
没有用于此练习。
#!/usr/bin/perl
use warnings;
use strict;
use Switch;
use DBI();
#
# _voting.pl
#
# Connect to the database.
my $dbh = DBI->connect("DBI:mysql:database=sms_voting;host=localhost",
"sisisi", "*********",
{'RaiseError' => 1});
my $sth = $dbh->prepare("INSERT INTO voting
(epoch, validity, choice, campaigns_id, candidates_id ) VALUES (?,?,?,?,?)");
open (LOGFILE, '/var/www/voting/votes.txt') or die("Could not open log file.");
my $errors = 0;
my $campaign_id = 0;
my $candidate_id = 0;
foreach my $line (<LOGFILE>) {
my ($vote, $epoch, $campaign, $validity,
$choice, $CONN, $MSISDN, $GUID, $Shortcode) = split(' ', $line);
# parse the field:value entries...
$campaign = substr $campaign, 8, 11, '';
$validity = substr $validity, 9, 6, ''; # during
$choice = substr $choice, 7, 10, ''; # Brown
# case statements to define correct foreign keys...
switch ($campaign) {
case ("ssss_uk_01B") { $campaign_id = 1 }
case ("ssss_uk_01C") { $campaign_id = 2 }
case ("ssss_uk_01D") { $campaign_id = 3 }
case ("ssss_uk_01E") { $campaign_id = 4 }
case ("ssss_uk_01F") { $campaign_id = 5 }
case ("ssss_uk_01G") { $campaign_id = 6 }
}
switch ($choice) {
case ("Brown") { $candidate_id = 1 }
case ("Cameron") { $candidate_id = 2 }
case ("Balls") { $candidate_id = 3 }
case ("Green") { $candidate_id = 4 }
case ("Boring") { $candidate_id = 5 }
case ("Tupele") { $candidate_id = 6 }
}
if ($epoch && $validity && $choice && $campaign_id && $candidate_id ) {
$sth->execute($epoch, $validity, $choice, $campaign_id, $candidate_id);
# debug
print "$epoch $validity $choice \n"; # 1161048980 during Green
next;
}
$errors++;
}
close (LOGFILE);
# debug
print qq(errors=$errors\n);
对于 foreach 的每个循环,$campaign 和 $choice 变量都通过 switch 语句运行,以定义候选 ID 和活动 ID 数字。这些外键将分别映射到候选人和竞选表。
有关数据库模型,请参见:http ://acookson.org/wp-content/themes/cookie_23112012/img/sms_voting.png。
IE
INSERT INTO voting (epoch, validity, choice, campaigns_id, candidates_id )
VALUES (1161048980,'during','Brown', 1, 1),
(1161048980,'during','Tupele', 3, 5), ... etc
在 votes.txt 中检测到的任何空值都会导致 $errors 变量增加。
该脚本似乎成功循环通过 votes.txt 但未能初始化:$campaign_id 和 $candidate_id 变量。完成后,errors=19 被打印到终端;我的样本数据 votes.txt 中的总行数;这意味着该文件中的每一行都未能插入到数据库中。
mysql> select * from voting;
Empty set (0.00 sec)
证实了这一点。
该脚本没有报告语法错误;因此它的级别更低。没有开关就可以正常工作;因此,这在一定程度上缩小了范围。但是我看不到开关的问题,所以在这里寻求建议。