Beginner's Tutorial for CGI using Perl Language
For and Foreach

For and Foreach Loops

For Loop

This has been for long the favorite loop of many programmers I know. For, what wouldn't a programmer give for for.

for(initialization ; condition ; next) {

For is extremely useful when you have to execute a given set of instruction a limited number of time with little or no changes. Lets see an example. How about a small program that will print out the multiplication tables.


#Multiplication table...
my $n=4; # We want the multiplication table of 4
for (my $i=1; $i<=10; $i++) {
	my $ans = $i * $n;
	print "$i x $n = $ans\n";

If you don't know these tables, I recommend that you take the time to learn it. It would come in handy when you are programming. Sometimes at least.


Think of foreach as a 'for' for lazy programmers. With foreach one can access all items in a array one at a time.

foreach $varaible (@array) {

The variable '$variable' have all the element of '@array' array one at a time. Let try a example...


print "New Year's Resolutions for Internet Junkies\n\n";

#Make a array with all the resolutions
my @resolutions = ("I will figure out why I *really* need 7 e-mail addresses.",
"I will stop sending e-mail to my wife.",
"I resolve to work with neglected children -- my own.",
"I will answer snail mail with same enthusiasm with which I answer my e-mail",
"I resolve to back up my hard drive daily...well, 
	once a week...okay, monthly then...or maybe...",
"I will spend less than one hour a day on the Internet.",
"When I hear 'Where do you want to go today?' I won't say 'MS Tech Support.'",
"I will read the manual.",
"I will think of a password other than \"password\".",
"I will stop checking my e-mail at 3:00 in the morning.");

foreach $plan (@resolutions) {
	print "$plan\n";

This tiny program will print out all the resolutions one by one. In the first round, the first resolution will be stored in the "$plan" variable and printed. In the second round, it will be the second resolution and so on.

Subscribe to Feed