perl - prompting multiple questions to user (yes/no & file name input) -


i want ask user multiple questions. have 2 types of questions: y/n or filename input. i'm not sure how place nice if structure. , i'm not sure if should use 'else' statements too. this? have far:

print "do want import list (y/n)?"; # first question yes/no $input = <stdin>; chomp $input;     if ($input =~ m/^[y]$/i){ #match y or y         print "give name of first list file:\n";         $list1 = <stdin>;          chomp $list1;         print "do want import gene list file (y/n)?";             if ($input =~ m/^[y]$/i){                  print "give name of second list file:\n" # can use $input or need define variable?;                  $list2 = <stdin>;                  chomp $list2;                  print "do want import gene list file (y/n)?";             }     } 

one word: abstraction.

the solution chose not scale well, , contains repeated code. write subroutine prompt hides of complexity us:

sub prompt {   ($query) = @_; # take prompt string argument   local $| = 1; # activate autoflush show prompt   print $query;   chomp(my $answer = <stdin>);   return $answer; } 

and promt_yn asks confirmation:

sub prompt_yn {   ($query) = @_;   $answer = prompt("$query (y/n): ");   return lc($answer) eq 'y'; } 

we can write code in way works:

if (prompt_yn("do want import list")){     $list1 = prompt("give name of first list file:\n");     if (prompt_yn("do want import gene list file")){          $list2 = prompt("give name of second list file:\n");          # if (prompt_yn("do want import gene list file")){          # ...     } } 

oh, seems want while loop:

if (prompt_yn("do want import list")){     @list = prompt("give name of first list file:\n");     while (prompt_yn("do want import gene list file")){         push @list, prompt("give name of next list file:\n");     }     ...; # @list } 

the @list array. can append elements via push.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -