Question

This program throws an error. The problem is that I have to use switch case. How can I do this in Perl?

#use strict;
#use warnings;
my $input = print "Enter the number";
$input = <STDIN>;
switch($input){
    case "1" {print "UPC"}
    case "2" {print "ES"}
    case "3" {print "MS"}
    else {print "Enter the correct value"}
}
Was it helpful?

Solution

You need to import Switch to use it:

use Switch;

However, Switch has been deprecated. See this question: Why is the Switch module deprecated in Perl?

Some alternatives (and their experimental status) are discussed here: http://perldoc.perl.org/perlsyn.html#Switch-Statements

In summary, if you're using Perl >5.10.1, you can use the following for a non-deprecated, non-experimental switch:

use v5.10.1;
for ($var) {
    when (/^abc/) { $abc = 1 }
    when (/^def/) { $def = 1 }
    when (/^xyz/) { $xyz = 1 }
    default { $nothing = 1 }
}

OTHER TIPS

Perl's built in version of the case statement is a little different:

use feature "switch";

given ($foo) {
        when (/^abc/) { $abc = 1; }
        when (/^def/) { $def = 1; }
        when (/^xyz/) { $xyz = 1; }
        default { $nothing = 1; }
    }

You can add a more traditional case statement with use Switch;, but this is deprecated as RobEarl points out.

Also, never comment out use strict; use warnings; as an attempt to fix problems!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top