Question

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();

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?

Was it helpful?

Solution

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 }
     }
}

I used Switch::Plain instead of Switch, as it is much safer (it doesn't use a source filter) and sufficient for your case.

OTHER TIPS

perlfaq7 - How do I create a switch or case statement?

Using the builtin function since 5.10

use 5.010;

use strict;
use warnings;

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 }
    };
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top