user2886545
user2886545

Reputation: 713

Iterate through a hash and an array in Perl

I have an array and a hash:

@arraycodons = "AATG", "AAAA", "TTGC"... etc.
%hashdictionary = ("AATG" => "A", "AAAA" => "B"... etc.)

I need to translate each element of the array for the corresponding value in hashdictionary. However, I obtain a wrong translation.....

To see the problem, I have printed $codon (each element of the array), but each codon is repeated several times..... and It shouldn't.

sub translation() {
    foreach $codon (@arraycodons) {
        foreach $k (keys %hashdictionary) {
            if ($codon == $k) {
                $v = $hashdictionary{$k};
                print $codon;
            }
        }
    }
}

I don't know if I've explained my problem well enough, but I can't go on with my code if this doesn't work...

Many thanks in advance.

Upvotes: 2

Views: 458

Answers (3)

Ashalynd
Ashalynd

Reputation: 12573

my @mappedcodons = map {$hashdictionary{$_}} 
                  grep (defined $hashdictionary{$_},@arraycodons);

or

my @mappedcodons = grep ($_ ne "", map{$hashdictionary{$_} || ""} @arraycodons);

Upvotes: 2

PP.
PP.

Reputation: 10865

You appear to be looping through the keys of your hash (also known as a "dictionary") to find your desired key. This defeats the purpose of a hash (also known as a "dictionary") - the primary advantage of which is ultra fast lookups of a key.

Try, instead of

foreach $codon (@arraycodons) {
    foreach $k (keys %hashdictionary) {
        if ($codon == $k) {
            $v = $hashdictionary{$k};
            print $codon;
        }
    }
}

this:

foreach $codon (@arraycodons) {
    my $value = $hashdictionary{$codon};
    print( "$codon => $value\n" );
}

or:

foreach my $key ( keys %hashdictionary ) {
    my $value = $hashdictionary{$key};
    print( "$key => $value\n" );
}

Upvotes: 3

user1598019
user1598019

Reputation:

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

}
}

Upvotes: 1

Related Questions