2013-01-16 117 views
1

我在此刻學習了perl,並有一個簡短的腳本來訪問數據庫(DBI模塊)來提取一些統計信息。下面發佈的代碼似乎有點重複,我不知道它是否可以簡化爲散列循環。在每個數據庫查詢的唯一區別是在myo_maps_study正則表達式在perl中循環散列

#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

你明顯知道如何使用佔位符,那麼爲什麼你決定*不*使用佔位符MYO值? – TLP

+1

這聽起來像你有一個好主意,你想要做什麼。我會嘗試一下,看看會發生什麼 –

+3

你最近應該做的是重新設計你的數據庫。如果將學習類型分成單獨的列而不是將其附加到'myo_maps_study',則可以使用帶有GROUP BY的單個查詢輕鬆獲取所有這些計數。它可能會更快,特別是如果您在該列上添加索引。 –

回答

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; 
}