switch case in perl

www.igif‮t‬idea.com

Perl provides a given-when statement to implement switch-case-like constructs. The given-when statement allows you to test a variable against multiple values and execute different blocks of code based on the value of the variable. Here's an example of how to use given-when in Perl:

my $fruit = "apple";

given ($fruit) {
    when ("apple") {
        print "It's an apple.\n";
    }
    when ("banana") {
        print "It's a banana.\n";
    }
    when ("orange") {
        print "It's an orange.\n";
    }
    default {
        print "It's not an apple, banana, or orange.\n";
    }
}

In this example, the given statement takes a variable $fruit as its argument, and the when statements test the value of $fruit against different strings. If $fruit matches a string, the code inside the corresponding when block is executed. If none of the when blocks match, the default block is executed.

If $fruit were "apple", the output would be:

It's an apple.

If $fruit were "banana", the output would be:

It's a banana.

If $fruit were "orange", the output would be:

It's an orange.

If $fruit were any other value, the output would be:

It's not an apple, banana, or orange.

Note that the given-when statement was introduced in Perl 5.10, so if you're using an older version of Perl, you won't be able to use this syntax. In older versions of Perl, you can use if-elsif-else statements to achieve similar functionality.