首页 文章

循环遍历perl中的哈希

提问于
浏览
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) . 最后将结果打印到终端

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

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

相关问题