Saturday, 31 December 2016

Switch statement in perl

Many programming languages offer the switch/case statement but the perl programming language does not have any default switch statement built into it. Some of the newer versions of perl however have a construct named given-when which somewhat resembles the switch statement. This is not available while coding by default & has to be enabled by via the 'use feature' statement.

The syntax for using given-when is that a given value is matched against a set of values & when a match is found the corresponding block of code gets executed. There is also a default statement which is executed in case no match is found.

given (value) {
          when (value1) { some code ; }
          when (value2) { some code ; }
          default { default result  ; }
        }

This article is describes in brief the usage of given-when construct in perl via a simple script.
Given below is the script:

[root@alive ~]# cat switch.pl
#!/usr/bin/perl -w
#

use warnings;

$|=1;
use feature qw(switch);

print "system running perl version $^V \n";

##testing switch statement##
#
my $x = 10 ;
my $y = 20 ;


print "enter value: " ;
my $z = <STDIN> ;

given($z) {
        when($x) { print "you entered the nmber $x \n" ; }
        when($y) { print "you entered the nmber $y \n" ; }
        default { print "default \n" ; }
        }


This is a simple script which first prints the version of perl running on the system. It then prompts the user to enter a value. The input is then matched against the when clauses & the corresponding code block is executed when a match is found & the default statement is executed in case no match is found. 

Note: As mentioned earlier the given-when construct is not enabled by default. To enable it I've used the statement use feature qw(switch)

Here's what happens when we execute the script.

[root@alive ~]# ./switch.pl
system running perl version v5.16.3
enter value: 10
you entered the nmber 10
[root@alive ~]# ./switch.pl
system running perl version v5.16.3
enter value: 20
you entered the nmber 20
[root@alive ~]# ./switch.pl
system running perl version v5.16.3
enter value: 30
default
[root@alive ~]#

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...