Tuesday, April 12, 2011

understanding if, if-else, elsif, unless, for, foreach and while loops in perl scripting

Sponsored Links
The following post explains  if, if-else, elsif, unless, for, foreach and while loops in perl scripting

syntax :
if ( condition ) { statement; }
if ( condition ) { statement1; } else { statement2)
if ( condition1 ) { statement1; } elsif ( condition2 ) { statement2; }
unless ( condition ) { statement;}
for (Initial_value; condition; operation_on_variable) { statement; }
for (min_value..max_value) { statement; }
foreach (@array_name) { print "$_\n"; }

See the example program for more clear view.

#!/usr/bin/perl
#Purpose - To understand the concept of conditionals.
#START
#modules used
use strict;

#Variables used
my $value1 = 5;
my $value2 = 10;
my $value3 = 15;
my $value4 = 15;
my $i = 0;
my @array = ("Linux", "Windows", "Solaris", "Unix");

    #---------------------------------------------------------------------
    #if loop
    if (1 < 2) {
        print "1 is less than 2\n";
    }
   
    #---------------------------------------------------------------------
    #if-else loop
    if (2 < 1){
        print "The system is mad\n";
    }
    else {
        print "2 is not less than 1, This machine is brilliant\n";
    }
   

    #---------------------------------------------------------------------
    #elsif loop
    if ($value3 > $value4) {
        print "$value3 is greater than $value4\n";
    }
    elsif ($value3 < $value4) {
        print "$value3 is less than $value4\n";
    }
    else {
        print "$value3 is equal to $value4\n";
    }
   
   
    #---------------------------------------------------------------------
    #unless loop
    unless ($value1 == $value2) {
        print "Oh the $value1 and $value2 are not same\n";
    }
   
    #---------------------------------------------------------------------
    #For loop
    for ($i=1; $i<=5; $i++) {print "$i\n";}
    for (1..5) {print "new_for_loop\n";}

   
    #foreach loop
    foreach (@array) {print "$_\n";}


    #---------------------------------------------------------------------
    #While loop
    while ($value1 < $value2) {
        print "$value1 is less than $value2\n";
        $value1 +=1;
        print "With 1 increment $value1\n";
    if ($value1 == $value2) {print "Now the values are same\n";}
    }

#END
Sponsored Links

No comments:

Post a Comment

Be nice. That's all.