1

我现在正在学习 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\$ 等

然后我可以执行我的数据库查询,$sth->execute(hash value, $date_stop, $date_start)并将查询的结果分配给具有 $hash_key 形式的标量(即 $n_myo_stress)。最后将结果打印到终端

我为糟糕的格式和缩进道歉,我不确定如何在堆栈溢出时执行此操作

4

1 回答 1

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;
}
于 2013-01-16T12:45:31.933 回答