.:: Welcome To My Personal Blog ::.

Saturday, March 5, 2011

Beginner's Guide To Travel With Perl - Part 4

Branching

We may have to use condition in some programs. The syntax will be the following:
if ( condition ) {
...
} elsif ( other condition ) {
...
} else {
...
}



Notice that the word else if will be written in “elsif”, and the second parentheses (‘{‘, ’}’) must be needed here.

Looping

To write a regular program, we may need to use loop. Loop helps us to run a particular piece of code over and over again. This is part of a general concept in programming called flow control.
Perl has several different functions that are useful for flow control, the most basic of which are “for”, “while”, “foreach” etc. When we use the “for” function, we must specify a variable that will be used for the loop index, and a list of values to loop over. Inside a pair of curly brackets, we can put any code we want to run during the loop.

Example:
for $i (1, 2, 3, 4, 5) {
print "$i\n";
}

This loop prints the numbers 1 through 5, each on a separate line.

There is a shortcut for defining loops is using “..” to specify a range of numbers. We can write (1, 2, 3, 4, 5) as (1 .. 5). We can also use arrays and scalars in the loop list. Let’s see another example:
@first_range = (1 .. 10);
$mid_value = 15;
@second_range = (20 .. 25);

for $i (@first_range, 14, $mid_value, @second_range) {
print "$i\n";
}

The output will then be the numbers from 1 to 10, 14, 15, and from 20 to 25.

The normal “for” loop can also be written simply like C. So the syntax can be:
for ($i = 0; $i <= $max; $i++) { ... } The syntax for “while” loop will be the following: while ( condition ) { ... } The syntax for “foreach” is like: foreach (@array) { print "This element is $_\n"; } Example:
@array = (1, 2, 3, 4, 5);
foreach (@array) {
print "This element is $_\n";
}

Check the output to realize this.


Help Links:

http://www.perl.com/pub/2000/10/begperl1.html
http://perldoc.perl.org/perlintro.html

http://www.perl.org/learn.html
http://learn.perl.org/books.html
http://learn.perl.org/tutorials/
http://www.perl.com/pub/2008/04/23/a-beginners-introduction-to-perl-510.html
http://docstore.mik.ua/orelly/perl2/prog/ch01_05.htm
http://www.tizag.com/perlT/perluserinput.php
http://www.tizag.com/perlT/perlchomp.php

http://perldoc.perl.org/functions/use.html
http://www.well.ox.ac.uk/~johnb/comp/perl/intro.html

http://www.sthomas.net/roberts-perl-tutorial.htm/ch22/use_strict_
http://docstore.mik.ua/orelly/perl/prog3/ch31_19.htm
http://debugger.perl.org/580/perldebtut.html
http://perldoc.perl.org/strict.html


. . . . . To be continued . . . . .

No comments:

Post a Comment

Popular Posts