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

后端 未结 3 1868
遥遥无期
遥遥无期 2021-02-15 15:43

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

3条回答
  •  -上瘾入骨i
    2021-02-15 16:31

    A while ago I end up with following:

    #!/usr/bin/perl
    use warnings;
    use strict;
    use Data::Dumper;
    
    
    if (&prompt_yn("CONTINUE")){
      my @res = split(" ",&prompt("ENTER INPUT")) ;
      print Dumper @res;
    }
    else{
      print "EXIT\n";
    }
    
    sub prompt_yn{
      my ($query) = @_;
      $query = $query . " (Y/N): ";
      print "$query";
      while (<>) {
        $_ =~ s/^\s+|\s+$//g;
        $_ =~ s/\r|\n//g;
        if ($_ =~ /\S/){
          if ($_ =~ /^y$|^yes$/i){
            # if you want information message about entered value uncomment this
            # print "You have entered Y\n";
            return 1;
          }
          elsif ($_ =~ /^n$|^no$/i){
            # if you want information message about entered value uncomment this
            # print "You have entered N\n";
            return 0;
          }
          else{
            # if you want information message about entered value uncomment this
            # print "You have entered wrong value try again: \n";
          }
        }
        print "$query";
      }
    }
    
    sub prompt{
      my ($query) = @_;
      $query = $query . ": ";
      print "$query";
      while (<>) {
        $_ =~ s/^\s+|\s+$//g;
        $_ =~ s/\r|\n//g;
        if ($_ =~ /\S/){
          return $_;
        }
        print "$query";
      }
    }
    

    Compared to previous solutions this handles empty inputs.

提交回复
热议问题