Checking the user input in perl for characters and length

My question is basically as the title says. How can I check a user inputted string is only certain characters long (for example, 3 characters long) and how do I check a user inputted string only contains certain characters (for example, it should only contain the characters 'u', 'a', 'g', and 'c') all in perl.

Test with it:

#!/usr/bin/perl
#
use strict;
use warnings;

print "Please, choose three of the following characters (u,a,g or c): ";
my $answer = <STDIN>;
chomp $answer;
if ($answer =~ /^[uagc]{3}$/) {
    print "Your choice is accepted\n";
}
else {
    print "Your choice is rejected\n";
}

Thanks Aia! I have another question actually. In Perl, how do you declare multiple keys to one value when it comes to hashes?

An example would be, say, I want four keys known as 'acg', 'acc', 'aca', and 'caa' to one value known as 'Phr'. And two keys known as 'gaa' and 'gac' to one value known as 'Rea'.

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my @phr = qw(acg acc aca caa); # used on method 1

my (%phrhash, %reahash);
@phrhash{@phr} = ('Phr') x @phr; # method 1
@reahash{'gaa', 'gac'} = qw(Rea Rea); # method 2

print Dumper \%phrhash;
print Dumper \%reahash;

Output:

perl test.pl
$VAR1 = {
          'aca' => 'Phr',
          'caa' => 'Phr',
          'acg' => 'Phr',
          'acc' => 'Phr'
        };
$VAR1 = {
          'gaa' => 'Rea',
          'gac' => 'Rea'
        };
1 Like

Thank you Aia!