Switch :: Plain - 为非数字输入抛出警告

时间:2014-03-27 12:35:42

标签: perl switch-statement redo nextuntil

这个程序会引发重做错误我怎么能解决这个问题

use strict;
use warnings;
use Switch::Plain;

my %data = (0 => "Enter the number",1 => "UPC",2 => "URL", 3 => "Elastic Search", 4 => "API", 5 => "MONGO", 6 => "TSV", 7 => "SQL", 8 => "JSON", 9 => "Enter the correct value");
my $input = "Enter the number:";


sub input(){
    print "Choose You Input Method"."\n";
    print "1.UPC"."\n";
    print "2.URL"."\n";
    print "3.Elastic Search"."\n";
    print $input;
    PROMPT: {
    chomp(my $input = <>);
     nswitch($input){
        case 1 : {print "UPC"."\n"}
        case 2 : {print "URL"."\n"}
        case 3 : {print "Elastic Search"."\n"}
        default: {"Enter the correct value"; redo PROMPT }

      }


}
}

input();

my $pinput = "Enter the number:";
sub pinput(){
    print "Choose Your Process Method"."\n";
    print "1.API"."\n";
    print "2.Mongo"."\n";
    print $pinput;
    $pinput = <>;
    chomp($pinput);
    nswitch($pinput){
       case 1 : {print "API"."\n"}
       case 2 : {print "MONGO"."\n"}
       default : {print "Enter the correct value"."\n"}
}
}

pinput();

抛出的错误是

Argument "" isn't numeric in numeric eq (==) at framework.pl line 21, <> line 1

如果用户输入中存在任何不匹配,例如用户输入空值或4,那么想法是重复子程序吗?

请帮我解决一下?

2 个答案:

答案 0 :(得分:2)

您可以通过添加0或乘以1

将输入转换为数字
$pinput = <> *1;

或在chomp

之后转换它
$pinput *= 1;

答案 1 :(得分:0)

查看How do I create a switch or case statement?

如果您使用的是5.10或更高版本,则可以使用内置方法执行此操作。然后,一种解决方案是将您匹配的内容视为字符串而不是数字:

use 5.010;

use strict;
use warnings;

print "Choose You Input Method"."\n";
print "1.UPC"."\n";
print "2.URL"."\n";
print "3.Elastic Search"."\n";

PROMPT: {
    chomp(my $input = <>);
    given ( $input ) {
        when( '1' )  { say "UPC" }
        when( '2' )  { say "URL" }
        when( '3' )  { say "Elastic Search" }
        default      { print "Enter the correct value"; redo PROMPT }
    };
}