【问题标题】:Switch::Plain - warning thrown for non-numeric inputSwitch::Plain - 对非数字输入抛出警告
【发布时间】:2014-05-06 10:33:37
【问题描述】:

这个程序重做时抛出错误我该如何解决这个问题

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,则想法是重复子例程?

请帮我解决一下?

【问题讨论】:

标签: perl switch-statement redo nextuntil


【解决方案1】:

您可以通过添加0,或乘以1,将输入转换为数字,

$pinput = <> *1;

或者在chomp之后转换

$pinput *= 1;

【讨论】:

  • 对于一个空值它可以工作,但如果用户输入 4 我只有 3 个 switch case 那么它不应该把他带到下一个子例程它应该重复相同的功能吗? @mpapec
  • @user3231692 不确定您指的是什么,但如果您的案例未涵盖4,则默认为default:
  • 是的,但它会打印错误值并传递给下一个函数,但我希望它打印默认函数并退出函数@mpapec
  • @user3231692 $data{$input} 将提供API 用于输入4
【解决方案2】:

查看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 }
    };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2017-08-24
    • 1970-01-01
    • 2019-12-14
    • 2013-11-15
    • 2013-10-20
    相关资源
    最近更新 更多