我现在正在学习perl并且有一个简短的脚本,我在其中访问数据库(DBI模块)以提取一些统计信息。下面发布的代码似乎有点重复,我想知道它是否可以简化为哈希循环。每个数据库查询的唯一区别是myo_maps_study
中的正则表达式#Get the number of myo stress studies
$sth = $dbh->prepare("SELECT count(myo_maps_study) FROM myo WHERE myo_maps_study ~ 'MYO[0-9]*\$' AND myo_date <= ? AND myo_date >= ?");
$sth->execute($date_stop,$date_start) or die "Couldn't execute myo stress query" . $sth->errstr;
my $n_myo_stress = $sth->fetchrow_array;
#Get the number of myo redistribution studies
$sth = $dbh->prepare("SELECT count(myo_maps_study) FROM myo WHERE myo_maps_study ~ 'MYO[0-9]*R\$' AND myo_date <= ? AND myo_date >= ?");
$sth->execute($date_stop,$date_start) or die "Couldn't execute myo rep query" . $sth->errstr;
my $n_myo_rep = $sth->fetchrow_array;
#Stress tomos
$sth = $dbh->prepare("SELECT count(myo_maps_study) FROM myo WHERE myo_maps_study ~ 'MYO[0-9]*T\$' AND myo_date <= ? AND myo_date >= ?");
$sth->execute($date_stop,$date_start) or die "Couldn't execute myo stress tomo query" . $sth->errstr;
my $n_stress_tomo = $sth->fetchrow_array;
#Rest tomos
$sth = $dbh->prepare("SELECT count(myo_maps_study) FROM myo WHERE myo_maps_study ~ 'MYO[0-9]*U\$' AND myo_date <= ? AND myo_date >= ?");
$sth->execute($date_stop,$date_start) or die "Couldn't execute myo rest tomo query" . $sth->errstr;
my $n_rest_tomo = $sth->fetchrow_array;
print "***** Imaging Statistics ************\n";
print "n_myo_stress: $n_myo_stress \n";
print "n_myo_rep: $n_myo_rep \n";
print "n_stress_tomo: $n_stress_tomo \n";
print "n_rest_tomo: $n_rest_tomo \n";
print "\n\n***********************************\n";
例如我可以创建一个哈希数组,其中键值为n_myo_stress,n_myo_rep等,它们的值是正则表达式MYO [0-9] \ $,MYO [0-9] * R \ $ etc
然后我可以使用$sth->execute(hash value, $date_stop, $date_start)
执行数据库查询,并将查询结果分配给格式为$ hash_key的标量(即$ n_myo_stress)。最后将结果打印到终端
我为糟糕的格式化和缩进道歉,我不确定如何在堆栈溢出时执行此操作
答案 0 :(得分:5)
您不需要哈希,您可以这样做:
$sth = $dbh->prepare("SELECT count(myo_maps_study) FROM myo WHERE
myo_maps_study ~ ? AND myo_date <= ? AND myo_date >= ?");
my @results;
for my $myo (qw(MYO[0-9]*$ MYO[0-9]*R$ MYO[0-9]*T$ MYO[0-9]*U$)) {
$sth->execute($myo, $date_stop, $date_start)
or die "Couldn't execute query for $myo: " . $sth->errstr;
push @results, $sth->fetchrow_array;
}