PERL FLOW CONTROL
Friday, August 29, 2014
By
Unknown
0
comments
In this post, we are diving one level deep into perl and we will explore and learn about the flow controls of perl, which includes the native top down approach, conditional jumps, iterations, etc.
By default, in perl, the approach is top down, ie when we run a perl script, the perl interpreter parses the code from top to bottom, but many a times we feel the need to change this default behaviour, we might want to do certain things based on some conditions. Thanks to perl, we can do it like other programming language with the help of "IF" and "UNLESS" statement.
In our real life, we often make a decision, based on certain logic, like if it is raining, we take umbrella, else we do not take it. Similarly, the same concept applies to perl too, it makes decision with "IF" AND/OR "UNLESS" Statements.
The "IF" Statement:
Lets look at the syntax of IF statement:
IF ( CONDITION ) { BLOCK }
This means if the condition is True, the Block of statements has to be executed.
Example:
#!/usr/bin/perl
use strict;
use warnings;
my $var1 = "perl";
my $var2 = "perl";
if ($var1 eq $var2)
{
print "Both the values of variables are same";
}
More General syntax:
if(LOGICAL) {BLOCK}
if(LOGICAL) {BLOCK1} else {BLOCK2}
In condition is True, BLOCK1 is executed, if the condition is False, BLOCK2 is executed.
if(LOGICAL) {BLOCK1} elsif(LOGICAL2) {BLOCK2} else {BLOCK3}
This is a check for multiple conditions, this says, if first condition is True, BLOCK1 is executed, if second condition is true, BLOCK2 is executed, if all the conditions are not true, the else BLOCK is executed.
if(LOGICAL) {BLOCK1}
elsif(LOGICAL2) {BLOCK2}
elsif(LOGICAL3) {BLOCK3}
elsif(LOGICAL4) {BLOCK4}
else {BLOCK5}
With that said, lets look at a very simple perl script:
[gray@ckserver Perl Programming]$ cat conditions.pl
#!/usr/bin/perl
#
my $super_password = "superpassword";
my $gen_password = "password";
my $user_input;
print "\n\n[#] Welcome Admin!! Log in with your password.\n\n";
print "[#] Enter Password : ";
$user_input = <STDIN>;
chomp($user_input);
if ($user_input eq $super_password)
{
print "\n[+] Welcome Super Admin!!\n";
}
elsif ($user_input eq $gen_password)
{
print "\n[+] Welcome User!!\n";
}
else
{
print "\n[+] Wrong Password!!\n";
}
[gray@ckserver Perl Programming]$ perl conditions.pl
[#] Welcome Admin!! Log in with your password.
[#] Enter Password : superpassword
[+] Welcome Super Admin!!
[gray@ckserver Perl Programming]$ perl conditions.pl
[#] Welcome Admin!! Log in with your password.
[#] Enter Password : password
[+] Welcome User!!
[gray@ckserver Perl Programming]$ perl conditions.pl
[#] Welcome Admin!! Log in with your password.
[#] Enter Password : test
[+] Wrong Password!!
[gray@ckserver Perl Programming]$
Thats all for this, hope this was fun and interesting...
Feel Free To Leave A Comment If Our Article has Helped You, Support Us By Making A Small Contribution, Thank You!
0 comments: