Conditional Statements in PERL - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Conditional Statements in PERL

Share This

Conditional statements help in decision making. If a condition is true, this block is executed otherwise the program control moves to the next instruction followed by the block.

In this language, numeric value 0 , string '0' or "" , a list having no elements () , and undef represent false in a boolean context. Negation of a true value by ! or not returns a special false value.

In this context, the conditional statements are discussed below.

if statement

A boolean expression is enclosed in if , based on the condition either of the the blocks is executed as shown below.

$x = 20; $y = 10; if ($x > y) { print "x is greater than y.\n"; }

if...else statement

An if statement can be followed by an optional else statement.


$x = 20; $y = 10; if ($x > y) { print "x is greater than y.\n"; } else { print "y is greater than or equals with x.\n"; }

if...elsif...else statement

An if statement can be followed by an elsif statement, the elsif represents else if .


$x = 20; $y = 10; if ($x > y) { print "x is greater than y.\n"; } elseif (x < y){ print "y is greater than x.\n"; } else { print "x is equals with y.\n"; }

unless statement

An unless statement consists of a boolean expression followed by one or more statements.


$x = 10; unless($x <= 0){ print("x is greater than 0\n") }

unless...else statement

An unless statement can be followed by an optional else statement.


$x = 10; unless ($x >= 5){ print("x is less than 5\n") } else { print("x is greater than or equal 5\n"); }

unless...elsif..else statement

Similar to if...elsif...else , an unless statement can also be followed by an elsif statement, which in turn is followed by an optional else statement.


$x = 1; unless($x > 5){ print("x is less than 5\n"); }elsif($x == 5){ print("x is 5\n"); }else{ print("x is greater than 5\n"); }

switch statement

In latest versions of Perl, switch statement can be used to compare value of a variable against various conditions.


my $color; my $code; print("Please enter a RGB color to get its code:\n"); $color = <STDIN>; chomp($color); $color = uc($color); given($color){ when ('RED') { $code = '#FF0000'; } when ('GREEN') { $code = '#00FF00'; } when ('BLUE') { $code = '#0000FF'; } default{ $code = ''; } } if($code ne ''){ print("code of $color is $code \n"); } else{ print("$color is not RGB color\n"); }

The ? : Operator

Let's check the conditional operator ? : which can be used to replace if...else statement. It has the general form Exp1 ? Exp2 : Exp3; where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.


#!/usr/local/bin/perl $age = 10; $status = ($age > 60 )? "Senior citizen" : "Not senior citizen"; print "$status\n";




Happy Exploring!

No comments:

Post a Comment