0

i'm learning perl, and i'm trying to write a program asks you to pick an amino acid and then keeps (randomly) guessing which amino acid you picked.

I would like to do it with arrays. so I declare first in the subroutine an array with the letters im looking for, then if theres a match print the variable if the match equals to variable name

if there's a match equals to variable name in subroutine how could print the variable content?

use warnings;
use strict;

print "Please type an aminoacid in one letter code; i'm going to tell you which one it is:\n";
chomp(my $aminoacid = <STDIN>);
my $aminoacid_is  = guessaa ($aminoacid);

sub guessaa {
    my @aminoacid_arryay = ("A","C","D","E","F","G","H","I","K","L","M","N","O","P",
                            "Q","R","S","T","V","W","Y");
    my($A)="Alanine";
    my($C)="Cysteine";
    my($D)="Aspartic_acid";
    my($E)="Glutamic_acid";
    my($F)="Phenylalanine";
    my($G)="Glycine";
    my($H)="Histidine";
    my($I)="Isoleucine";
    my($K)="Lysine";
    my($L)="Leucine";
    my($M)="Methionine";
    my($N)="Asparagine";
    my($O)="Stop";
    my($P)="Proline";
    my($Q)="Glutamine";
    my($R)="Arginine";
    my($S)="Serine";
    my($T)="Threonine";
    my($V)="Valine";
    my($W)="Tryptophan";
    my($Y)="Tyrosine";
    my($aa) = @_;
    foreach $a (@aminoacid_arryay) {
        if ($a eq $aa) {
            print  "$a","\n\n";
        }
    }
}
TLP
  • 66,756
  • 10
  • 92
  • 149
  • Does this answer your question? [Perl, access variable by name in an other scalar](https://stackoverflow.com/questions/6285652/perl-access-variable-by-name-in-an-other-scalar) – Günther Bayler Jul 13 '22 at 20:26
  • What you want is a hash, then do the lookup as `$aminoacid{$_}`. – TLP Jul 13 '22 at 21:56

2 Answers2

3

Why it's stupid to `use a variable as a variable name'

Create a hash.

my %aa_names = (
   A => "Alanine",
   C => "Cysteine",
   ...
);

say $aa_names{ $aa } // $aa;
ikegami
  • 367,544
  • 15
  • 269
  • 518
3

You use a hash as a lookup table for these kind of things:

use strict;
use warnings;

print "Please type an aminoacid in one letter code: ";
chomp(my $aminoacid = <>);
print guessaa($aminoacid);

sub guessaa {
    my %a = (
        "A" => "Alanine",
        "C" => "Cysteine",
        "D" => "Aspartic_acid",
        "E" => "Glutamic_acid",
        "F" => "Phenylalanine",
        "G" => "Glycine",
        "H" => "Histidine",
        "I" => "Isoleucine",
        "K" => "Lysine",
        "L" => "Leucine",
        "M" => "Methionine",
        "N" => "Asparagine",
        "O" => "Stop",
        "P" => "Proline",
        "Q" => "Glutamine",
        "R" => "Arginine",
        "S" => "Serine",
        "T" => "Threonine",
        "V" => "Valine",
        "W" => "Tryptophan",
        "Y" => "Tyrosine"
    );
    return $a{$_[0]} // "Aminoacid '$_[0]' not found";
}
TLP
  • 66,756
  • 10
  • 92
  • 149