moadeep
moadeep

Reputation: 4118

Looping through a hash in perl

I am learning perl at this moment and have a short script in which I access a database (DBI module) to pull out some statistics. The code posted below seems a little bit repetitive and I wonder whether it can be reduced to a hash loop. The only difference in each database query is the regular expression in 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";

For example could I create a hash array where the key values are n_myo_stress, n_myo_rep etc and their values are the regular expressions MYO[0-9]\$, MYO[0-9]*R\$ etc

Could I then execute my data base queries with $sth->execute(hash value, $date_stop, $date_start) and assign the results of the query to a scalar with the form $hash_key (i.e. $n_myo_stress). Finally printing the result to the terminal

I apologise for the poor formatting and indentation, I am unsure how to do this on stack overflow

Upvotes: 1

Views: 198

Answers (1)

TLP
TLP

Reputation: 67920

You don't need a hash, you can just do:

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

Upvotes: 5

Related Questions