向用户提示多个问题(是/否和文件名输入) [英] prompting multiple questions to user (yes/no & file name input)
问题描述
我想问用户多个问题.我有两种类型的问题:是/否或文件名输入.我不确定如何将这一切放入一个很好的 if
结构中.而且我不确定是否也应该使用else"语句.有人可以帮助我们吗?这是我目前所拥有的:
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)?";
}
}
推荐答案
一个词:抽象.
您当前选择的解决方案不能很好地扩展,并且包含太多重复的代码.我们将编写一个子程序 prompt
来隐藏大部分复杂性:
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;
}
现在是一个要求确认的 promt_yn
:
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")){
# ...
}
}
哦,看来你真的想要一个 while
循环:
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
}
@list
是一个数组.我们可以通过 push
来追加元素.
The @list
is an array. We can append elements via push
.
这篇关于向用户提示多个问题(是/否和文件名输入)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!