2

我有一个数组和一个哈希:

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

我不知道我是否已经很好地解释了我的问题,但是如果这不起作用,我将无法继续使用我的代码......

提前谢谢了。

4

3 回答 3

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" );
}
于 2013-10-30T12:33:24.243 回答
2
my @mappedcodons = map {$hashdictionary{$_}} 
                  grep (defined $hashdictionary{$_},@arraycodons);

或者

my @mappedcodons = grep ($_ ne "", map{$hashdictionary{$_} || ""} @arraycodons);
于 2013-10-30T12:32:13.520 回答
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"; 
    }

}
}
于 2013-10-30T12:30:42.847 回答