[Ilugc] [TIP] perl tutorial II (conditionals and looping)

  • From: girishvenkatachalam@xxxxxxxxx (Girish Venkatachalam)
  • Date: Sun, 4 Dec 2011 06:48:17 +0530

We will see conditionals and looping.

To begin with perl does not have the switch statement found in other languages.

There is also no break and continue. Instead you have last and next.

Most of perl's conditionals are written using the regex construct:

if(/\d/) {
} elsif(/\w/) {
}

Here is a complete example.

$ cat i.pl
$users = 'foo,boo';

if($users =~ /\d/) {
        print "digits\n";
} elsif($users =~ /\w/) {
        print "alnum\n";
}


Regular expressions are usually acted upon the default $_ special variable.

So if(/\d/) actually means if($_ =~ /\d/).

Anyway now let us focus on the core conditionals and looping facilities in perl.

We have already seen the if() condition before.

We have also seen the foreach()/for() iterator.

for() is just an alias for foreach().

$ cat i.pl

foreach($i = 0; $i < 10; $i++) {
        print $i . "\n";
}


Replace foreach with for and it will work the same.

We have seen the iterator idea already.

for $var (1 .. 100) {
          print $var . "\n";
}

Same thing can be written as

for(1..100) {
         print;
         print "\n";
}

Here we again see the default loop variable $_ working.

It is good not to focus on perl's tricks to begin with. Do things the
formal way.

We now have seen the if() conditional and the for() looping construct.

Of course we have while() and we can simulate switch statement too.

We will see that tomorrow.

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

Other related posts: