Monday, January 30, 2012

Learning PERL | Day 6


Hi friends! In our last blog learning session, we grabbed some knowledge about the flow of control in PERL programming by using ‘if-else’ statements. Let us understand today these ‘if-else’ statements by means of some examples.

Consider you are asked to build a program which can classify the customers in a bank as premium, important and regular customer on the basis of the balance they have in their bank accounts. Classification is to be made like this: 

“those customers with amount deposited over $1,000,000 are to be treated as premium; those having amount deposited between $500,000 and $1,000,000 are to be treated as important customer; and finally, those left, i.e., customers with deposits below $500,000 are to be treated as regular customers.”

This problem can be converted into a PERL program which can be used to distinguish the various classes of customers. Let us see how it is done:

if ($balance > 1000000)
{
  print “\nPremium Customer.”;
}
elsif ($balance > 500000)
{
  print “\nImportant Customer.”;
}
else
{
  Print “\nRegular Customer.”;
}


In the program illustrated above, the flow is designed in such a way that there is the need of only one condition to be specified in the body of execution. ‘Body of Execution’ is the block below each condition, it is included in the curly-brackets ( { <body> } ).

One more thing to notice here is that we do not put terminator (;) after the if or elsif or else statement. It is because the statement as a whole does not terminates at the same line, if found correct, it’s body will be executed, which is in the next line starting with ‘{‘ and ending with ‘}’. It is a common mistake to put terminator after the flow statement.

One more that I want to discuss today is the use of comments in our programs. Suppose you are working on a big-big and complex program which uses various formulae and statements. It is a usual thing that you may not be able to grasp your own coding if viewed later. So, to keep our program meaningful to us and to other programmers, we use some statements which help us in grabbing the idea about our program. These statements are completely ignored by the PERL interpreter.

In PERL, comments begin with ‘#’ symbol. In other words, if you put ‘#’ in a line, all the characters after become invisible to interpreter. Let us re-write the above program using comments to make it more illustrative.

if ($balance > 1000000)          # first condition
{
  print “\nPremium Customer.”;   #  Body of first condition
}
elsif ($balance > 500000)        # second condition
{
  print “\nImportant Customer.”; #  Body of second condition
}
Else                             #  Final condition
{
  Print “\nRegular Customer.”;  #  Body of final condition
}


This concludes today’s learning session on PERL learning blog. Hope you are finding these learning sessions interesting and easy to understand.


With Warm Regards,
Yajur Kumar
(PERL Programming Expert)

Thursday, January 26, 2012

Learning PERL | Day 5


Hi friends! Till now, I think we have grabbed sufficient to start out study of flow of control in PERL programming. By flow of control, I mean how the control of program passes from one step to another. It can be understood as the main deciding factor or program flow logic.
In our previous blog learning session, I introduced ‘if-else’ statements; however, I left their deep understanding for today. So, let us understand the functioning of these ‘if-else’ statements today.

The ‘if’ statement is used to specify a particular condition, often, a logic statement. It can be understand by following syntax:

if (<condition>)
{
   <Steps to follow>
}
Consider the following code fragment to understand this syntax:

if ($x==0)
{
    print “\nThe value of x is zero”;
}

The above code fragment is used to check whether the value of x is zero. To judge this, we first used if statement with condition “$x==0”, which means the statement that “x equals zero”. If this condition is found true, the statement body will be executed, which prints “The value of x is zero.” on the screen, otherwise, it will be skipped.

If it is needed that provided the first condition is skipped, the program will check for the second condition, ‘if-else’ or ‘else’ statement is used. The general syntax of ‘if-else’ nesting, which can be extend to the limit we need, is:

if (<condition_1>)
{
    <Steps to follow>
}
else if (<condition_2>)
{
   <Steps to follow, provided condition_1 is wrong>
}
else
{
   <Steps to follow, provided all conditions are wrong>
}

We will understand the ‘if-else’ nesting with a suitable example in our tomorrow’s learning session on this blog.
Hope you enjoyed today’s learning session on PERL.
Happy Republic Day to my readers from India.

As always, if you find anything difficult or if you have any suggestion, please feel free in discussing with me.
With Warm Regards,
Yajur Kumar
(PERL Programming Expert)


Tuesday, January 24, 2012

Learning PERL | Day 4


Hi friends! Let’s recall what we grabbed in our yesterday’s blog session. Yesterday, I told you about operators in PERL, which was actually an overview. So, today we will learn a little more about operators.

Occasionally, we need to change the value of the variables in the program. This can be done by applying some relation e.g., if the value of some constant A is 5, but you now need it to be 10, this can be done by:

A = A + 5;

Shorthand of writing this expression is:

A + = 5;

Similarly, if any similar expression can be shorthanded. Let us take another example. 

C = C – A;

Is equivalent to writing:

C - = A;

Now, if I need to increase or decrease the value of a variable by unity, this can be done in a very handy way by either adding ‘++’ or ‘--’ after or before it. For example, if I need to increase the value of variable x by 1 in the program, then the coding will be:

x++;

or

++x;

Now, one question might arising in your mind is what’s the difference between “x++” and “++x”? The answer is somewhat tricky to those who are new learners of programming. Actually, “x++” means “addition is carried out after the variable is used in the specified operation” and “++x” means “addition is carried out before the variable is used in any further operation”.

If you are a new learner and facing difficulty in understanding above paragraph, just leave it for today. You will be able to grab the concept in the next blog learning sessions for sure.
Similarly, if you need to decrease the value of variable y by unity, use the code:

y--;

or

--y;

Let us know about some other basic operators. However, we will learn their implementation in our coming blog learning sessions.

You might me familiar with “>” and “<”, known as “greater than” and “less than” operators. In addition, there are some other logic operators viz. “>=”, known as “greater than or equal to”; “<=”, known as “less than or equal to”; “!=”, known as “not equal to”; “==”, known as “is equal to”. 

The above described logic operators are used in certain logic operations. For example, consider the following code fragment:

if ($var1 > $var2)
{
   print “\nFirst variable is greater than second variable.”;
}

The first statement of this code fragment is a logic statement to judge whether first variable that is, var1 is greater that second variable, that is, var2.  
Let us take another example to understand the operation of other logic operators.
Consider following code fragment:

if ($x != 0)
{
    print “\nValue of x is not zero.”;
}

The above code fragment is whether to check the value of x is not zero. 

If I need to check whether the value of two variables are equal, following code can be used:

if ($var_1 == $var_2)
{
   print “\nVariable 1 equals Variable 2.”;
}

Note that in the above code fragment, we used ‘==’, that is, ‘equal to’ sign two times. A common mistake can be the use of single ‘equal to’ operator. This will lead to assigning of value of $var_2 to var_1. Hence, the following coding is wrong:

If ($var_1 = $var_2)
{
   print “\nVariable 1 equals Variable 2.”;
}


So, this concludes our today’s learning session on PERL learning blog. In our next sessions, we will deal with more complex coding in PERL.
As always, if you find anything difficult or if you have any suggestion, please feel free in discussing with me.

With Warm Regards,
Yajur Kumar
(PERL Programming Expert)

Monday, January 23, 2012

Learning PERL | Day 3


Hi friends! Yesterday we learnt about different datatypes used in PERL. The most important thing in any program is the governing logic which is implemented by using various formulae and algorithms. To implement formulae, we need to use certain operators with our variables so that we could get the desired output value.

Let us introduce ourselves today with the operators used in PERL programming.
Here are some elementary things for beginners. For simple addition, we use ‘+’ sign, as we used in our first program. Similarly, for subtraction, ‘-‘; for multiplication, ‘*’; for division, ‘/’. Also, ‘**’ is used for exponentiation. 

For example, if I wish to store value of variable term xy , that is, ‘x raised to the power y’ in dependent variable ‘f’, the code fragment should be:
$f =  $x ** $y;

One common mistake anyone can make is confusing with complex formula like:
$avg = $var1 + $var2 / 2;

The above written code-fragment is intended to calculate average value of two variables, but, is, however, wrongly coded. The reason is that precedence of ‘/’, that is, division operator over ‘+’, that is addition. To use the code correctly, we should use braces:

$avg = ($var1 + $var2) / 2;

,which is correct now.

I found by my learning experience that cramming the precedence sheet of operators is a really put everything in mesh. So, I recommend my readers to better make full use of braces ‘()’. Using braces avoids unnecessary confusion and possibility of wrong coding.

In many places, we need to store two strings stored in separate variables to one variable. For example, $first_name contains first name of employees in a company and $last_name contains last name of employees and what we need is to store their full name in single variable, we use ‘.’, that is, ‘dot’ operator. The operation is occasionally referred as concatenation. 

For understanding, consider following code-fragment:

$first_name = “John”;
$last_name = “Smith”;
$full_name = $first_name . $last_name;
print $full_name;

The output of above code fragment will be John Smith.

Another interesting operator is ‘x’, that is, English alphabet small x. It is used for concatenation of string to itself in specified number of times.
For example, consider the following code fragment:

$string = “Hello”;
print $string x 3;

The above code will produce HelloHelloHello as output. So, for remembering, it could be think as like multiplying the string into any number of times. If we specify zero as the concatenation number, the string will lead to no value or empty value, specified by “ “.

Some operators used in producing statements or strings in the program are ‘\n’ and ‘\t’, which are known as newline and tab character respectively. The newline character, ‘\n’, is used to produce output in new line. ‘\t’ represents a tab.

For example, consider the following code fragment:

print “Line 1\nLine 2”;

This code will produce output as:

Line 1
Line 2

But, what if I need to print exactly ‘Line 1\nLine 2’ on the screen? That’s a tricky one. It can be done by using single quotes e.g., ‘string’, instead of double quotes e.g., “string”.
Hence, the following code fragment:

print ‘Line 1\nLine 2’;

will print exactly

Line 1\nLine 2


So, this concludes your today’s learning session on PERL blog. I hope you are still finding it relatively easier than C and C++, if you have used them before. Otherwise, there is nothing to ponder upon.

Please feel free in e-mailing me your suggestions and questions, if any, at yajurlive@live.com


With Warm Regards,
Yajur Kumar
(PERL Programming Expert)

Sunday, January 22, 2012

Learning PERL | Day 2


Welcome back friends!

Yesterday we learn about writing a simple addition program in PERL. To recall you, we coded a program for simple addition in which we used two variables, “$x” & “&y”:
 
$x = 100;
$y = $x + $x;
print $y;

I stated in my previous blog that variables are used for storing ‘varying data’ that we need or generated in the program. So, you may have noticed one thing about the variable names e.g., in “$x” and “$y”, why we are using this “$” sign before any variable? The answer is related to the identification of these variables as ‘variables’ by the PERL interpreter. The “$” sign tells the PERL interpreter that it is dealing with a variable.

A variable name, which starts from “$” sign, may contain letters(a-z, A-Z), numbers(0-9), a special character “_”, known as underscore or a mixture of these. Example of variable names are $value1, $value2, $max_value, $min_value etc. There is a limit on number of letters you can use in variable names, but, don’t worry, I’m sure you will never need to jump over it.

The variable names should be descriptive and handy to you. Such as if you are writing a program to compute EMI on loan amount, and you use variable names as “$x” and “$y”, and so on, your program may become uninformative after a few steps, that’s you waste most of your time in remembering what x stands for, what y stands for etc. I suggest using mixed type variable names; however, you can omit vowels in words. For example, a good variable for loan amount can be “$amt_loan”.

For those who have used to code in ‘C’ before, they may have familiar with the ‘Datatypes’. For beginners, datatypes simply define what type of data you are entering or what type of information you want in return from the machine. 
For example, in some cases you may need integer values like 1423, 88383 etc., and in some other cases you may need to input contact names as “John Smith”, “Yajur Kumar” etc. So, datatypes simply tells what type of data the program is dealing with.

PERL uses three types of datatypes, namely, scalars, arrays and hashes. Today we only deal with them in short and will learn about them in detail in our next learning sessions in this blog.

Scalars can have any kind of value, viz. a character, a whole number, an integer, or a string. Scalars variable names starts with “$” symbol, as we learned in our first program. Further, for now just remember that array variables initialize with “@” symbol and hash variables starts with “%” symbol.

Also, I like one thing of PERL that it does not need to declare any variable before using it like other programming languages e.g., C and C++. We can use the variables directly without bothering about their declaration in the program.

So, this concludes your second day at PERL learning blog. Tomorrow we will go through some basics in scalar data types.

Hope you find today’s blogpost interesting.

With Warm Regards,
Yajur Kumar
(PERL Programming Expert)

Friday, January 20, 2012

Learning PERL | Day 1

Hello Friends! I spent a long, long time in advancing my knowledge over PERL-the most amazing programming language to deal with. I usually saw new programmers worrying much about dealing with PERL, they treat it as a threat to learn after seeing it's 1300-1400 paged books. Since, I learned it in a slight different way, and find it enjoying, I think I should spread the words out here in my daily blog.

In my this daily basis learning blog, I will introduce the basics of PERL programming language and it's my humble belief that if you visit and read this blog course-ware daily, you will learn PERL in an easiest and enjoyable way. The notes you get from here will help you understanding PERL basics which can help you in your homework, in college studies and in many day-to-day tasks in programming because PERL is everywhere.


So, let us start with the introduction of PERL first. PERL is a programming language created in 1987. It stands for Practical Extraction and Report Language. First of all, on our first learning day, please note that you will need to download PERL to run its programs on your computer. Mostly, if you are using your college computer, there is a possibility that it is already installed there, since, it is widely used as a learning tool. In case, you find it is not there, you can download its free copy from PERL website.


Let’s start our day 1 of programming. To write a PERL program, you need a text editor, for which I recommend notepad++, which is downloadable for free from Notepad++ website. I recommend using notepad++ because it offers many additional features like helping you in commands, different colors for variables and keywords etc., which may help you recognizing your program easily. Alternatively, you can use notepad also. Please note that using word processing software like Microsoft Word can produce unexpected results since they add formatting data to your codes. So, it is not suggested to use any word processing software. Also, I recommend saving your PERL codes with “.pl” extension. Although it is not necessary to do so because PERL won’t bother about filename extensions, but, in this way it looks nice and also some operating systems does not allow saving a file without any extension.

So, let us start with the simplest program on our first day. It is, addition of two numbers. The source code of this program is:

$x = 100;
$y = $x + $x;
print $y;

Type the code fragment given above in notepad++ and save it under filename “SimpleAddition.pl”.

Now, let us understand what the symbols used in above code means.

$x and $y are known as variables and are used for storing data in the program. You can understand them as initially empty baskets. Although, they may contain garbage values if you do not initialize them with any finite values first.
Our second line of code, “$y = $x + $x;” means “put the value of ($x + $x) in $y”. This is the main formula of our program.
Lastly, there is “print $y” which means “print whatever contained in $y”.
Also, you might have noticed that we have put a semicolon “;” after every line. It is used to terminate a particular statement and is known as terminator.

Well, so, till now we have written a basic addition code in PERL. Let us check if our program gives an expected output. To get the output, run the program by commanding “perl SimpleAddition.pl”, which should return you value “200”. Since, we do not define the preciseness we need in our program, in some systems, the output may be like “200.00000000000”.

So, that’s over for today. Today we learn some basics of writing a program in PERL and tried a simple program. Well, you know, this is a good start for your first day as a beginner. In my next blogs, I will tell you about how to write more complex and tricky programs and some more basics of PERL.

Hope you find this blog learning session enjoyable. In case you have further query, please feel free in posting your comment.

With Warm Regards,
Yajur Kumar
(PERL Programming Expert)