[Ilugc] [TIP] perl III more looping

  • From: girishvenkatachalam@xxxxxxxxx (Girish Venkatachalam)
  • Date: Mon, 5 Dec 2011 06:33:19 +0530

Just like the if() condition in languages there is an unless()
condition in perl.

It is just the opposite of if.

$j = 6;

unless($j eq 6) {
        print "j is not 6";
}

if($j eq 6) {
        print "j is 6";
}

You can also write conditionals like this:

print "I matched" if (/here/);

or:

print "Not matching" unless(/here/);

Of course this construct only makes sense inside a loop since $_ gets
 set only in such conditions. And this need be a for() iterator.

It can also be a file read with the <> (diamond operator).

Now we will see the while loop.

It is just like C. Except that there is a dollar everywhere.
$i = 26;

while($i > 0) {
        print "$i\n";
        $i--;
}


There is also do while().

$i = 26;

do {
        print "$i\n";
        $i--;
}while($i > 0);

We have an example to obtain user input and then a conditional code.

$ cat i.pl
print "Please enter a number:";
$i = <>;

chomp($i);
if($i eq 1) {
        print "i is 1\n";
} elsif($i eq 100) {
        print "is is 100\n";
} else {
        print "i is neither 1 nor 100\n";
}
$ perl i.pl
Please enter a number:

Note that chomp() is used to remove a training newline from input.

<> reads a line or lines from standard input STDIN depending upon whether
 the LHS is a scalar($var) or array(@a).1

Now we will see how to do break and continue  using last and next:

$ cat i.pl

@arr = (1,2,2,4, "something" , 3, 5, 56, "more string", "last", 334);

for(@arr) {
        unless(/\d/) {
                print "Got string:$_\n";
        }
        if($_ eq 2) {
                print "I am continuing\n";
                next;
        }
        if($_ eq 56) {
                print "I am breaking the loop\n";
                last;
        }
}

Enough for today.

-Girish


-- 
G3 Tech
Networking appliance company
web: http://g3tech.in ?mail: girish at g3tech.in

Other related posts: