in reply to Creating hash with my imput
Another way. For input entered by a user (even you!), it is usually very important to verify the input. Note that in a statement like
Readonly my $RX_DNA => qr{ [ATCGatcg]+ }xms;
a => (fat comma) is used instead of an = (assignment) operator. If you don't want to use Readonly, make the statement
my $RX_DNA = qr{ [ATCGatcg]+ }xms;
instead.
>perl -wMstrict -e "use Readonly; ;; Readonly my $RX_ID => qr{ \d+ }xms; Readonly my $RX_DNA => qr{ [ATCGatcg]+ }xms; ;; my %pairs; print qq{please enter a comma-separated id/dna pair: }; PAIR: while (chomp(my $pair = <STDIN>)) { last PAIR unless $pair; my ($id, $dna) = $pair =~ m{ \A ($RX_ID) \s* , \s* ($RX_DNA) \z }xms; if (defined $id) { $pairs{$id} = $dna; } else { print qq{'$pair' unrecognizable: rejected. \n}; } print qq{please enter another id/dna pair: }; } ;; use Data::Dumper; print Dumper \%pairs; " please enter a comma-separated id/dna pair: 123, ata please enter another id/dna pair: 222 cgcg '222 cgcg' unrecognizable: rejected. please enter another id/dna pair: 222, cgcg please enter another id/dna pair: 33, abcd '33, abcd' unrecognizable: rejected. please enter another id/dna pair: 33 ,acGT please enter another id/dna pair: $VAR1 = { '123' => 'ata', '33' => 'acGT', '222' => 'cgcg' };
|
|---|