Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

I want to ask the user multiple questions. I have two types of questions: Y/N or filename input. I'm not sure how to place this all into a nice if structure. And I'm not sure if I should use 'else' statements too. Could someone help we with this? This is what I have so far:

print "Do you want to import a list (Y/N)?"; # first question yes/no
my $input = <STDIN>;
chomp $input;
    if ($input =~ m/^[Y]$/i){ #match Y or y
        print "Give the name of the first list file:\n";
        my $list1 = <STDIN>; 
        chomp $list1;
        print "Do you want to import another gene list file (Y/N)?";
            if ($input =~ m/^[Y]$/i){
                 print "Give the name of the second list file:\n" # can I use $input or do I need to define another variable?;
                 $list2 = <STDIN>;
                 chomp $list2;
                 print "Do you want to import another gene list file (Y/N)?";
            }
    }
like image 648
user1987607 Avatar asked Aug 07 '13 12:08

user1987607


1 Answers

One word: Abstraction.

The solution you currently chose does not scale well, and contains too much repeated code. We will write a subroutine prompt that hides much of the complexity from us:

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

And now a promt_yn that asks for confirmation:

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

We can now write your code in a way that actually works:

if (prompt_yn("Do you want to import a list")){
    my $list1 = prompt("Give the name of the first list file:\n");
    if (prompt_yn("Do you want to import another gene list file")){
         my $list2 = prompt("Give the name of the second list file:\n");
         # if (prompt_yn("Do you want to import another gene list file")){
         # ...
    }
}

Oh, so it seems you actually want a while loop:

if (prompt_yn("Do you want to import a list")){
    my @list = prompt("Give the name of the first list file:\n");
    while (prompt_yn("Do you want to import another gene list file")){
        push @list, prompt("Give the name of the next list file:\n");
    }
    ...; # do something with @list
}

The @list is an array. We can append elements via push.

like image 54
amon Avatar answered Sep 22 '22 02:09

amon