我有一个数组和一个哈希:
@arraycodons = "AATG", "AAAA", "TTGC"... etc.
%hashdictionary = ("AATG" => "A", "AAAA" => "B"... etc.)
我需要将数组的每个元素转换为hashdictionary中的相应值。但是,我得到了错误的翻译......
为了看问题,我打印了$ codon(数组的每个元素),但每个密码子重复几次.....并且它不应该。
sub translation() {
foreach $codon (@arraycodons) {
foreach $k (keys %hashdictionary) {
if ($codon == $k) {
$v = $hashdictionary{$k};
print $codon;
}
}
}
}
我不知道我是否已经很好地解释了我的问题,但是如果这不起作用我就不能继续使用我的代码......
非常感谢提前。
答案 0 :(得分:3)
您似乎正在遍历哈希键(也称为“词典”)以找到所需的键。这违背了哈希(也称为“词典”)的目的 - 其主要优点是对密钥进行超快速查找。
尝试,而不是
foreach $codon (@arraycodons) {
foreach $k (keys %hashdictionary) {
if ($codon == $k) {
$v = $hashdictionary{$k};
print $codon;
}
}
}
这样:
foreach $codon (@arraycodons) {
my $value = $hashdictionary{$codon};
print( "$codon => $value\n" );
}
或:
foreach my $key ( keys %hashdictionary ) {
my $value = $hashdictionary{$key};
print( "$key => $value\n" );
}
答案 1 :(得分:2)
my @mappedcodons = map {$hashdictionary{$_}}
grep (defined $hashdictionary{$_},@arraycodons);
或
my @mappedcodons = grep ($_ ne "", map{$hashdictionary{$_} || ""} @arraycodons);
答案 2 :(得分:1)
my @words = ("car", "house", "world");
my %dictionary = ("car" => "el coche", "house" => "la casa", "world" => "el mundo");
my @keys = keys %dictionary;
foreach(@words) {
my $word = $_;
foreach(@keys) {
if($_ eq $word) { # eq, not ==
my $translation = $dictionary{$_};
print "The Spanish translation of $word is $translation\n";
}
}
}