open (OUTPUT, ">>./output.txt") or die "Cannot open the output file: $!"; foreach my $id (@ids) { my $sth = $dbh->prepare("select long_string from my_table where id=?"); $sth->execute($id); my $long_string = $sth->fetchrow_array(); $sth->finish(); undef($sth); my %count; my @letters = split("", $long_string); foreach my $letter (@letters) { $count{$letter}++; } undef(@letters); undef($long_string); # Print out the counts for each string print OUTPUT "$id\t" . ($count{A} || 0) . "\t" . ($count{B} || 0) . "\t" . ($count{C} || 0) . "\t" . ($count{D} || 0) . "\t" . ($count{E} || 0) . "\t" . ($count{F} || 0) . "\t" . ($count{G} || 0) . "\t" . ($count{H} || 0) . "\t" . ($count{I} || 0) . "\t" . ($count{J} || 0) . "\t" . ($count{K} || 0) . "\t" . ($count{L} || 0) . "\t" . ($count{M} || 0) . "\t" . ($count{N} || 0) . "\t" . ($count{O} || 0) . "\t" . ($count{P} || 0) . "\t" . ($count{Q} || 0) . "\t" . ($count{R} || 0) . "\t" . ($count{S} || 0) . "\t" . ($count{T} || 0) . "\t" . ($count{U} || 0) . "\t" . ($count{V} || 0) . "\t" . ($count{W} || 0) . "\t" . ($count{X} || 0) . "\t" . ($count{Y} || 0) . "\t" . ($count{Z} || 0) . "\n"; undef(%count); } close (OUTPUT) or die "Cannot close the output file: $!";