YouTip LogoYouTip

Perl Switch Statement

# Perl switch Statement [![Image 4: Perl Conditions](#) Perl Conditions](#) A **switch** statement allows testing a variable against multiple values. Each value is called a case, and the variable being tested is checked against each **switch case**. Switch case execution is based on the **Switch** module, which is not installed by default. ### Installing the Switch.pm Module **Using CPAN to Install** Open a command window, enter the `cpan` command, then enter the `install Switch` command: # cpan cpan> install Switch // Install cpan> exit // Exit **Using apt-get on Ubuntu** sudo apt-get install libswitch-perl ### Syntax The syntax format is as follows: ## Syntax use Switch; switch(argument){case 1{print"Number 1"}case"a"{print"String a"}case[1..10,42]{print"Number in list"}case(@array){print"Number in array"}case /w+/{print"Regex pattern match"}case qr/w+/ { p r int"Regex pattern match"}case(%hash){print"Hash"}case(&sub){print"Subroutine"}else{print"No match for previous conditions"} } Here are the rules for the switch statement: * The **switch** statement's parentheses can contain a scalar parameter of any type. * A switch can contain any number of case statements. Each case is followed by a value to compare and a colon. * The scalar after the case statement is compared to the scalar in the switch statement to check for equality. * When the tested variable equals the constant in a case, the statement following the case is executed until a **break** statement is encountered. * The **switch** statement can have an optional **else** at the end, which executes if none of the cases match. * After a case matches, the code block for that case is executed, and then execution exits the switch statement. * If we need to continue executing subsequent cases after a match, we need to add a **next** statement. ### Flowchart !(#) ## Example #!/usr/bin/perl use Switch; $var = 10; @array = (10, 20, 30); %hash = ('key1' =>10, 'key2' =>20); switch($var){case 10{print"Number 10n"}case"a"{print"String a"}case[1..10,42]{print"Number in list"}case(@array){print"Number in array"}case(%hash){print"In hash"}else{print"No matching condition"}} Executing the above program, the output is: Number 10 Next, let's look at an example using **next**: ## Example #!/usr/bin/perl use Switch; $var = 10; @array = (10, 20, 30); %hash = ('key1' =>10, 'key2' =>20); switch($var){case 10{print"Number 10n"; next; }# Continue execution after match case"a"{print"string a"}case[1..10,42]{print"Number in list"}case(@array){print"Number in array"}case(%hash){print"In hash"}else{print"No matching condition"}} Executing the above program, the output is: Number 10Number in list [![Image 6: Perl Conditions](#) Perl Conditions](#)
← Prop Textarea PlaceholderPerl Conditions β†’