本文介绍了perl 中的控制流验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码,它有 switch 语句工作正常,但如果用户输入大于 3 或空白文本,那么它应该留在第一个子例程中我如何在 perl 中执行此操作
This is my code which has switch statement works fine but if user enters greater than 3 or blank text then it should stay in first sub routine how can i do this in perl
use strict;
use warnings;
use Switch;
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;
$input = <>;
chomp($input);
switch($input){
case 1 {print "UPC"."\n"}
case 2 {print "URL"."\n"}
case 3 {print "Elastic Search"."\n"}
else {print "Enter the correct value"."\n"}
}
}
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);
switch($pinput){
case 1 {print "API"."\n"}
case 2 {print "MONGO"."\n"}
else {print "Enter the correct value"."\n"}
}
}
pinput();
如果用户输入诸如 4 或空白数据之类的内容,则不应将其传递给另一个子例程,而应保留在同一个子例程中,我该怎么做?
if user enters something like 4 or blank data it should not pass to another sub routine it should stay on the same sub routine how can i do this?
推荐答案
用redo
将提示代码包裹成块:
Wrap the prompt code into a block with redo
:
#!/usr/bin/perl
use warnings;
use strict;
use Switch::Plain;
PROMPT: {
chomp(my $input = <>);
nswitch ($input) {
case 1 : { print "UPC\n" }
case 2 : { print "URL\n" }
case 3 : { print "Elastic Search\n" }
default : { print "Enter the correct value\n" ; redo PROMPT }
}
}
我使用了 Switch::Plain 而不是 Switch,因为它更安全(它不使用源过滤器)并且足以满足您的需求.
I used Switch::Plain instead of Switch, as it is much safer (it doesn't use a source filter) and sufficient for your case.
这篇关于perl 中的控制流验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!