In this article we will go through various loops in PERL. Loops are used to perform iterative tasks over certain control conditions.
The For Loop in PERL :
- Initialization counter
- Condition checking counter
- Increment/decrement counter
The for loop has three counters (c-style) :
You can run it your end to see the output !
The ForEach Loop in PERL :
- Foreach operates on each element of an Array
- This array may come form Keys of a Hash/Associative-Array
- Some array operations(reverse/sort) are allowed in the foreach loop
- Default variable can take place if the element is not specified
- This array may be the default array of Arguments (@_)
It is very much self explanatory .
Here is an foreach code that you can run at your end :
This code iterates over the *.pl files in present directory. In VLSI Automation you may have to use such loops very frequently to iterate over files in a directory.
In the below example , we hand create a list and we iterate over it using the foreach loop :
This is a very common use of the foreach loop in PERL, however in most of the cases the list is not created by hand , instead it comes from some other part of the code as a output.
By Now you have noticed the difference of the for-loop and the foreach loop.
While and Do-While Loop in PERL :
You already know the while loop from c-language. Also you might be familiar with the do-while.
The functioning of the while loop is described in the below code snippet :
The code snippet is self explanatory as you read trough it.
The below code-snippet does your tour of the do-while loop functioning in PERL :
The meaning of the code snippet is self-explanatory.
Until and Do-until Loops in PERL :
The until loop continues executing as long as its test condition is false (i.e. until it becomes true).
The below code snippet explains the usage of the until and do-until loop :
The above code snippet is self-explanatory.
Loop Control : Next & Last
The Next and the Last serves the same purpose as continue and break keywords from c-language. Now it is new easier for you to understand the below points :
- The next and last operators allow you to modify the flow of your loop.
- It is not at all uncommon to have a special case; you may want to skip it, use next.
- Or a special case you want to quit when you encounter it, use last.
The code snippet mentioned above is self-explanatory.
The entire article is narrated in the video below :
Courtesy : Image by Jae Rue from Pixabay