Tuesday, September 8, 2009

Conditional and Loops:
Let me explain looping constructs other than Swith-case.
if-elsif-else
Following is the syntax for if-elsif-else .
if(condition)
{
......;
}
elsif(condition)
{
.........;
}
else
{
..........;
}

Following is the contradicted version of it

unless(condition)
{
........;
}
if the condition returns false, then the set the statements in between braces gets executed.
This is similar to if(!condition)

Braces after the if statement are required if there are bunch/block of statements to execute.
Following example explains in detail...

my $var=1;
if($var==1)
{
print "Bunch of Statements"."\n";
}
$var=0;
unless(!$var==1)
print("I am in unless condition");

Output:
Bunch of Statements
I am in unless condition

While statement
Following is the syntax for While conditional statement

while (condition)
{
........;
}

Following is the contradicted version of it

untill(condition)
{
...........;
}

Following is the example for while conditional statement

my $num=1;
while($num)
{
print "I am in While"."\n";
$num=0;
}
until ($num==1)
{
print "I am in untill"."\n";
$num=1;
}

Output:
I am in While
I am in untill

For Loop

for(variable_initialization;condition;iteration)
{
........;
}

Following is the example for 'for' loop

my $num=3;
my $vi;
for($vi=0;$vi<=$num;$vi++)
{
print $vi."\n";
}

Output
0
1
2
3

Foreach statement

Following is the syntax for 'foreach' statement

foreach(condition)
{
.............;
}

Example

my @ar=("One","Two","Three");
foreach(@ar)
{
print "List element $_"."\n";
}

Output:
One
Two
Three

After such a long time I am posting few of my learning's on Perl...

Variable Scoping:
In general variables are declared using "my".
my $var= "hello";
Actually its not required. Just use
$var="hello";
Both the statements print "hello".
But the second statement creates global variables throughout the program, which is not recommended.
Using 'my' creates lexically scoped variables. Say bunch of statements surrounded by curly-braces.
The variables declared in between braces are different.

my $var="Hello";
my $num=1;
if($num==1)
{
my $var1="World";
print $var."\n"; #prints Hello
print $var1."\n"; #prints World
}
print $var1; #prints nothing

Output:
Hello
World

Using "my" in combination with a 'use strict;' at the top of the Perl script means that the interpreter will pick up certain common programming errors.
Add 'use strict;' at the top of the script and execute the same script. The final print statement 'print $var1;' would display compile-time error and fail to execute the script.
So add 'use strict;' in the program, which is recommended.