FLOW CONTROL : UNLESS STATEMENT

Friday 29 August 2014
Posted by Unknown
In the last post we learnt about the basic PERL FLOW, and we also learnt that we can alter the flow of code depending on our needs. We also learnt about conditional statements viz IF statement. When we want to make some decisions we can use IF statement, based on which a block of code is executed.

Here in this post we will learn about another CONDITIONAL STATEMENT, the UNLESS statement. This is exactly the opposite of IF statement. We know in IF statement if the condition is True, only then some BLOCK of code is executed, but with UNLESS statement, BLOCK of code will be executed if the condition is FALSE

UNLESS works just like IF, but its just the opposite, in IF the statements in blocks are executed if the LOGIC is true or condition is true, but in UNLESS the block is executed only when the condition is false.

unless(LOGIC) {BLOCK}

This means, unless ( LOGIC IS FALSE ) { Execute this part of the code }

So we can say that:

unless(LOGIC) {BLOCK} is equal to if(!LOGIC) {BLOCK}

With that said, lets try this small Perl script to testify:


[gray@ckserver Perl Programming]$ cat un.pl
#!/usr/bin/perl

use strict;
use warnings;

my $a = 10;

unless($a == 9)
{
    print "\nI am executing coz the condition is false..\n";
}

[gray@ckserver Perl Programming]$
[gray@ckserver Perl Programming]$ perl un.pl

I am executing coz the condition is false..


So its very clear from the example script that, if we use unless, the condition has to be false .

Thats all for this post, have fun.

PERL FLOW CONTROL

Monday 18 August 2014
Posted by Unknown
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...

More About Operators

Sunday 17 August 2014
Posted by Unknown
Hello readers, hope you are having fun with perl. In the last post we learnt about the operators used in perl with Numbers and Strings. In this post we will see few more usage of operators..

The Auto Increment and Decrement:

Like most other Programming language, Perl also gives leverage of using Pre and Post Increment/Decrement of numbers.

Pre Increment: The value is incremented first, and then the expression is evaluated.
Pre Decrement: The value is decrement first, and then the expression is evaluated. 
Post Increment : The expression is evaluated first, then the value is incremented.
Post Decremented : The expression is evaluated first, then the value is decremented.

Example:

#!/usr/bin/perl
#

use strict;
use warnings;

# Pre Increment block

my $var1 = 5;
print ++$var1 + 10;
print "\n";

# Pre Decrement block

my $var2 = 5;
print --$var2 + 10;
print "\n";

# Post Increment block;

my $var3 = 5;
print $var3++ + 10;
print "\nValue of \$var3 : ",$var3;
print "\n";

# Post Decrement block;

my $var4 = 5;
print $var4-- + 10;
print "\nValue of \$var4 : ",$var4;
print "\n";


[gray@ckserver Perl Programming]$ perl operators.pl
16
14
15
Value of $var3 : 6
15
Value of $var4 : 4
[gray@ckserver Perl Programming]$


Concatenation Operators:
'.' with strings, helps in concatenation, i.e joining strings

#!/usr/bin/perl
#

use strict;

my $g = "Yo Yo ";
my $h = "Honey Singh!";
print $g.$h."\n";

[gray@ckserver Perl Programming]$ perl operators_1.pl
Yo Yo Honey Singh!
[gray@ckserver Perl Programming]$



Note For Offline helps, at the shell type:

[gray@ckserver Perl Programming]$ perldoc
Usage: perldoc [-h] [-V] [-r] [-i] [-v] [-t] [-u] [-m] [-n nroffer_program] [-l] [-T] [-d output_filename] [-o output_format] [-M FormatterModuleNameToUse] [-w formatter_option:option_value] [-L translation_code] [-F] [-X] PageName|ModuleName|ProgramName
       perldoc -f PerlFunc
       perldoc -q FAQKeywords

The -h option prints more help.  Also try "perldoc perldoc" to get
acquainted with the system.                        [Perldoc v3.14_04]
[gray@ckserver Perl Programming]$
[gray@ckserver Perl Programming]$ perldoc perldoc

Thats all for this post, have fun..

Perl Operators

Wednesday 13 August 2014
Posted by Unknown
Operators play a very crucial role in any programming language. As other programming language, the basic operators for perl remains the same, Addition, Subtraction, Multiplication and Division.

Seems simple, but things gets little complicated when there are several operators in a single statement. Here comes "precedence" and "associativity" to the rescue.

Operators in precedence with associativity:

1. **        Associativity: right
2. *,/,%    Associativity: left
3. +,-        Associativity: left

Let us try to understand precedence first with an example statement below:
    2**2+4/2-2+3%5
    => 4+4/2-2+3%5
    => 4+2-2+3%5
    => 4+2-2+3
    => 6-2+3
    => 7

Associativity, means the operation direction to be followed when operators of same precedence are in a statement. From the above example, when we reached line "4+2-2+3", perl found that operators of same precedence was in the line, hence it followed the associativity rule, which was from left to right to evaluate the expression.


So far, we dealt with the Numerical Operators with which we perform/calculate mathematical expressions. Now let us focus on COMPARISON operators where we would compare numbers and/or strings.


Operation                          Num version         String version
less than                                                      <                                    lt
less than or equal                                     <=                                 le
greater than                                                >                                    gt
greater than or equal                               >=                                 ge
equal to                                                        ==                                  eq
not equal to                                                  !=                                  ne
compare                                                       <=>                             cmp

These COMPARISON operators evaluates to either a True or False, but here is the catch...
Everything in perl is true, except:
a. The empty string "" and "0" or any expression that evaluates to these values
b. Any numeric expression that evaluates to numeric 0
c. Any value that is not defined.

String Operator comparison:
While comparing strings, we use
- eq and ne operators


Three-value compare statements:
    - If $a set to 4, 3 <=> $a return -1
    - if $a set to 4, 4 <=> $a return 0
    - if $a set to 5, 5 <=> $a return 1

    - if $b set to Perl, 'Basicperl' cmp $b return -1 , Because, in ASCII value of first letter(B) in Basicperl is less than first letter(P) in Perl.
    - if $b set to Perl, 'Perl' cmp $b return 0, as Both the ASCII vales matches
    - if $b set to Perl, 'Pert' cmp $b return 1, because, ASCII values till the 3rd letter was same, but on the 4th letter, ASCII of t is greater than l

With that said, lets summarize the whole post with this small perl script:

#!/usr/bin/perl
#


use strict;
use warnings;


# Example to show precedence and associativity
print 2**2+4/2-1+3%5;
print "\n";

# Example to show that a null string is false
my $test = "";
if($test)
{
print "baam\n";
}
else
{
print "Ouch\n";
}


# string comparisons
#

print "ad" lt "ab";
my $b = "Perl";
print 'Basicperl' cmp  $b;
print "\n";
print "Pert" cmp $b;
print "\n";


Thats all for this post, hope it was helpful..

ALL ABOUT VARIABLES

Tuesday 12 August 2014
Posted by Unknown
In this post we will learn about scalar variables and various conventions of naming variables.

A variable is a storage container which stores values either provided by user or maybe hardcoded by programmer in a script. These variables stores values temporarily in memory for further operation or for whatsoever purpose.

We can store anything in SCALAR variable, like numbers or strings. Perl itself converts the data to its data type in memory. Unlike C language, we do not have to explicitly define a variable as int, char, float, etc. In perl anytime we want to store any value, we just have to assign the value to variable and leave the rest on perl interpreter to decide what kind of data we entered, we need not be bothered about it.

RULES FOR NAMING VARIABLES

1. If "use strict" is used in our script, we must define our variables using the function "my"
    Ex: my $variablename;

2. A variable name must start with a '$' symbol.

3. A variable name may contain alphanumeric characters and underscores.

4. The first character in the variable name after the '$' symbol must be a letter.

5. A variable name must be upto 255 characters.

6. Variable Names must be case sensitive, ie. $ABC not equal to $abc.

7. A Variable Name cannot start with a Number.

A SCALAR variable used with double quotes will interpolate to the value of the variable.

With that said, lets check this small perl script.

#!/usr/bin/perl

use strict;
use warnings;


my $arg1 = "Computer Korner";
my $arg2 = " is a great group.\n";
my $arg3 = " members are awesome.";

print "$arg1 $arg2";

print "${arg1}'s $arg3";


We notice that in the second print statement, the variable name arg3 is enclosed within curly braces, this is necessary because we have a single quote after the variable name in the second print statement, and to keep perl out of any confusion we place the variable name within curly braces.

Note: This is due to the fact that certain ASCII characters within double quotes have special meanings.

An interesting situation:

What if we declare a variable and we don't assign a value to it and try to print the variable?
This will create an error, as an unassigned variable when printed or used has a value as "undefined".

Example:


#!/usr/bin/perl

use strict;
use warnings;

my $name;
print "$name";

The above will produce an error.


That's all for this part, hope it was interesting.

Feel free to comment for any doubts.

More about PERL Syntax

Saturday 9 August 2014
Posted by Unknown

From the last chapter, we now know how to execute a perl program, and few rules of how to write a basic perl script.

In this page, we will dive more into the syntax of perl and will find out how it looks and handles data.
A perl script contains multiple statements, and we know every statement in perl ends with a semi-colon.
A statement in perl, might contain zero or more expression.
AN EXPRESSION IS A PIECE OF PERL CODE THAT EVALUATES TO SOME VALUE.
From the previous perl example:

chomp($name);

This is a statement contains an expression which is "chomp($name)", and this expression evaluates to some value which is known as the result.

For Perl, every data is SCALAR, which is the simplest kind of data.
SCALAR data might be a string or numbers. We might think of numbers or strings as an entirely different entity, but Perl uses them interchangeably.

Some example of SCALAR data:

"perlbasic".'perl', "456" (strings)
4,7.01, -2 (numbers)

Primary rules:
Strings are always surrounded by single or double quotes.
Numbers should not be surround by any types of quotes.

Strings in Perl are not a set of characters. We know C Language sees a string as a set of characters, but Perl sees a string as a single entity.
Example:
The word "perl", which in other programming language like C, "perl" is a combination of "p,e,r,l" which is an array of characters. But in Perl the word or SPECIFICALLY the string is a single entity.

Though strings are enclosed within single or double quotes, but the way Perl looks the string inside them is little different.

In a single quoted string ('string'), what we type is what we get,ie.,anything  starting from the single quote and until the next single quote found will be printed.

So what if we want a word to have a single quote? Example 'don't'.........
In this case or in similar ones, we need to use "\" before the single quote.
Eg:
print 'don't'; <-- This is an error
print 'don\'t'; <-- Correct way

We know "\n" creates a new line, but when used within single quotes will literally print \n on the screen. This will not create a new line.

Single quoted string can span multiple lines i.e,
print 'twinkle twinkle
little star
how i wonder
what you are';

The above spanning of a single string to multiple lines is accepted.

For double quoted strings, certain ASCII characters have special meaning which we will talk later, for now lets say if we want to print email address or dollar symbol we need to escape the characters with backslash.

\n within double quotes will create a new line.

Example:
print "subir@computerkorner.org"; <-- Error
print "subir\@computerkorner.org"; <-- Correct

print "$5"; <-- Error
print "\$5"; <-- Correct

print "\n" will create a new line.
print "\a" will create a short beep.
print "\t" creates a horizontal tab
and so on...

SUMMARY
So with all those in mind,  let us check this small perl script:

------ scalar_usage.pl ------

#!/usr/bin/perl

use strict;
use warnings;

print 'Todays date is 10/08/2014';
print '\n';
print "\n";
print 'It\'s great to learn perl';
print "\n";
print "My email address : subirsutradhar2014\@gmail.com\n";
print "DON'T SPAM MY INBOX\n";
print 'This is
the end of
this
tutorial';
print "\n";

[gray@ckserver Perl Programming]$ perl scalar_usage.pl
Todays date is 10/08/2014\n
It's great to learn perl
My email address : subirsutradhar2014@gmail.com
DON'T SPAM MY INBOX
This is
the end of
this
tutorial
[gray@ckserver Perl Programming]$

That's all for this part, with a thought that you all learnt something new............ I'll be happy to read your views on it.

Thank you for reading.


The First Perl Program

Friday 8 August 2014
Posted by Unknown


In this page, we can see how a perl program looks and how it is executed, we will also look at the syntax, few rules while writing a perl program.

Lets have a quick peek of a Perl Program and see how does it look

To write a perl program, open up your favourite text-editor.

Note: Do remember to save all perl programs with ".pl" extension


[gray@ckserver Perl Programming]$ ls -l greet.pl
-rw-rw-r--. 1 gray gray 675 Aug  9 08:42 greet.pl
[gray@ckserver Perl Programming]$
[gray@ckserver Perl Programming]$ chmod 774 greet.pl
[gray@ckserver Perl Programming]$
[gray@ckserver Perl Programming]$ ls -l greet.pl
-rwxrwxr--. 1 gray gray 675 Aug  9 08:42 greet.pl
[gray@ckserver Perl Programming]$ ./greet.pl
Enter Your Name : Subir Sutradhar
Hello, Subir Sutradhar
! How are you..
Hello again Subir Sutradhar, Welcome to our Perl Basics Tutorials
[gray@ckserver Perl Programming]$
[gray@ckserver Perl Programming]$
[gray@ckserver Perl Programming]$ cat greet.pl
#!/usr/bin/perl
#
# Description        :    The First Hello World Program
# Date             :    9th Aug, 2014
# Author         :    Subir Sutradhar
#########################################


use strict; # An important line

use warnings; # Another important line

print "Enter Your Name : "; # print a question to the default STDOUT ie. screen

my $name; # declare a variable in memory named $name

$name = <STDIN>; # Take input from default input ie. Keyboard

print "Hello, $name! How are you..\n"; # printing to the screen

chomp($name); # removes new line character from the end of the user input

print "Hello again $name, Welcome to our Perl Basics Tutorials\n";

# Program Ends

[gray@ckserver Perl Programming]$


Lets understand the program now..

Interpreter Location : The first line "#!/usr/bin/perl" tells the path where the perl interpreter is located and this should be the first line of any perl program, NO OTHER LINE NOT EVEN A COMMENT SHOULD BE WRITTEN BEFORE THIS LINE.

Comments/Remarks : We can make comments or remarks like every other programming language, using the "#" symbol,which implies that any line that starts with "#" symbol is a comment line.

Note: The # symbol in the very first line tells about the path to perl interpreter and is not a comment symbol.

Every Statement in a perl program ends with a semi-colon ";"

Next, in the program, "use strict" and "use warnings" are two important lines very useful for new perl programmers, which changes rule to interpret a perl script.

use strict - Informs the interpreter to use all rules to be followed syntactically in the perl program, if any mistakes found it will inform during the compile time.

use warnings - Causes the program to give warnings if something iffy or confusing is found by the perl interpreter during the run time of the perl script.


With that said, now we understand the basic syntax of a perl script, which is easy.

Executing a perl program:

A newly created script will not have the execute bit turn on, until umask in your system is defined in such a way that the execute bit turns on by default, which is really a bad practise security wise.

Anyways, if it is not on, we can either turn it on or execute the perl program in the following way..

[gray@ckserver Perl Programming]$ ls -l greet.pl
-rw-rw-r--. 1 gray gray 675 Aug  9 08:42 greet.pl
[gray@ckserver Perl Programming]$ perl greet.pl
Enter Your Name : ^C
[gray@ckserver Perl Programming]$

To turn on the execute bit:
[gray@ckserver Perl Programming]$ chmod +x greet.pl

or,

[gray@ckserver Perl Programming]$ chmod 774 greet.pl

and then,

[gray@ckserver Perl Programming]$ ./greet.pl

Thats all for this part, hope you found it interesting.

Thank you for reading.

For any doubts feel free to comment....
Welcome to Perl Basics

Popular Post

Total Pageviews

- Copyright © Love with Perl Scripting -Perl Programming Language- Powered by Computer Korner - Meet Us At Facebook Page -