Login

Join for Free!
119284 members
table of contents table of contents

Biology Articles » Bioinformatics » Introductory Workbook on Perl for Biology Students » 7. Perl program depicting loop - functions

7. Perl program depicting loop - functions
- Introductory Workbook on Perl for Biology Students

The aim of this program is to show the use of loops like while, until, for, foreach in the Perl language. Loops are used if we need to perform a certain action for a number of times. 

 

In the present exercise, for the “until” condition, we assign a value (“venkat”) to a scalar variable $r. We then ask the user to enter a value. This value will be assigned to $i. The <STDIN> command is to tell the program that the user needs to give the value during the execution. Its abbreviation is Standard Input. When a program comes across the command, it stops and waits for the user to give the input. Once the input is given it takes the value for further execution.

 

So, in the 4th line the program checks whether the value of $r is present in $i (venkatraman). If the value is present it jumps to the 9th line. Otherwise it keeps printing “wrong password” and again asks the user to enter the value.

 

In the line 11 we used for loop to print the numbers from 0 to 9 and to print each number in a new line. We initialized the $i to 0 and specified the condition that it should be doing the loop until $i is less than 10 and incremented each time by 1. The body of for loop has a print statement to print the value of $i with a \n so that it prints it in a new line.

 

In line 17, each value from the array variable @ar is passed to the scalar variable $i. The value is then incremented by 2 and printed on the screen. This way all the values of the array are incremented by 2 and printed.

 

The while loop is used to print numbers from 0 to 5. We first initialize $k to 0 and then specify the condition ($k<5) in the While and perform the print operation and incrementing the value of $k by 1. This way the values of $k are printed from 0 to 4.

 

  1. #while, until, for, foreach, operation
  2. $r="venkat";
  3. $i=<STDIN>;
  4. until($i=~$r)
  5. {
  6. print"wrong password\n";
  7. $i=<STDIN>;
  8. }
  9. print"Welcome\n";
  10. #forloop
  11. for($i=0;$i<10;$i++)
  12. {
  13. print"$i\n";
  14. }
  15. #increment every element by 2
  16. @ar=(0..5);
  17. foreach$i(@ar)
  18. {
  19. $q=$i+2;
  20. print"$q.";
  21. }
  22. print"\n";
  23. #while
  24. $k=0;
  25. while($k<5)
  26. {
  27. print"$k\n";
  28. $k++;
  29. }
  30. exit;

 

RESULTS:

venkat

Welcome

0

1

2

3

4

5

6

7

8

9

2.3.4.5.6.7.

0

1

2

3

4


rating: 3.70 from 114 votes | updated on: 30 Jan 2009 | views: 95830 |

Rate article:







excellent!bad…