http://www.perlmonks.org?node_id=1063902

sahusonu has asked for the wisdom of the Perl Monks concerning the following question:

I m woking on protein coding problem . one amoni acid code for more than codon.suppose
%CodonMap = ( 'GCA'=>'A', 'GCC'=>'A', 'GCG'=>'A', 'GCU'=>'A') %reverse=reverse(%CodonMap); for($i=0;$i<4;$i++) { $value.=$reverse{'A'}; print "$value\n"; }
how to get all different codon for A.

Replies are listed 'Best First'.
Re: how extract values of hash via key
by Corion (Patriarch) on Nov 22, 2013 at 09:39 UTC
    %reverse= reverse(%CodonMap)

    This does not do what you think it does.

    A hash key in Perl can only have one value. Use Data::Dumper to look at the result:

    use Data::Dumper; %reverse= reverse(%CodonMap) print Dumper \%reverse;

    You will need to construct your reverse map manually, for example by looping through all keys and values:

    use Data::Dumper; my %reverse; while( my( $k,$v )= each %CodonMap) { $reverse{ $v }||= []; push @{ $reverse{ $v }}, $k; }; print Dumper \%reverse;

    Then, you will need to adapt your program logic to cater for the fact that you don't have simple scalars in %reverse anymore.

Re: how extract values of hash via key
by hippo (Bishop) on Nov 22, 2013 at 09:47 UTC

    Keeping your initial declaration of the hash, we can do:

    my %CodonMap = ('GCA'=>'A', 'GCC'=>'A', 'GCG'=>'A', 'GCU'=>'A'); my @acodes = (); for my $key (keys %CodonMap) { next unless $CodonMap{$key} eq 'A'; push @acodes, $key; } print join ("\n", @acodes, '');

    There's probably a more efficient way, but at least you now have a working algorithm.

      grep is doing the job nicely:

      my @acodes = grep { $CodonMap{$_} eq 'A' } keys %CodonMap;
Re: how extract values of hash via key
by mendeepak (Scribe) on Nov 22, 2013 at 09:45 UTC

    Site itself asks this before posting

    Use:  
    <p> text here (a paragraph) </p>
    and:  <code> code here </code>
    to format your post
    

    It will be useful for others to read.
    And about your question please reffer this multiple values for one key in hash, might be useful.

    *=*=*dEEPAk*=*=*
Re: how extract values of hash via key
by BillKSmith (Monsignor) on Nov 22, 2013 at 19:01 UTC
Re: how extract values of hash via key
by kcott (Archbishop) on Nov 22, 2013 at 23:42 UTC

    G'day sahusonu,

    Welcome to the monastery.

    Your simplest solution might be this:

    my %reverse; push @{$reverse{$CodonMap{$_}}}, $_ for keys %CodonMap;

    Here's an example with some additional (bogus) data to show this is extensible:

    #!/usr/bin/env perl -l use strict; use warnings; my %CodonMap = (GCA=>'A', GCC=>'A', GCG=>'A', GCU=>'A', UVW=>'B', XYZ= +>'B'); my %reverse; push @{$reverse{$CodonMap{$_}}}, $_ for keys %CodonMap; print "A codons: @{$reverse{A}}"; print "B codons: @{$reverse{B}}";

    Output:

    A codons: GCA GCU GCG GCC B codons: UVW XYZ

    -- Ken