现在我正在学习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等,它们的值是正则表达式MYO0-9\$、MYO0-9*R\$ etc
然后,我是否可以使用$sth->execute(hash value, $date_stop, $date_start)执行数据库查询,并将查询结果赋给形式为$hash_key (即$n_myo_stress)的标量。最后将结果打印到终端
我为糟糕的格式和缩进道歉,我不确定如何在堆栈溢出时做到这一点
发布于 2013-01-16 20:45:32
你不需要哈希,你可以这样做:
$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;
}https://stackoverflow.com/questions/14358539
复制相似问题