The Wayback Machine - https://web.archive.org/web/20240912154301/https://www.geeksforgeeks.org/perl-loops-for-foreach-while-do-while-until-nested-loops/
Open In App

Perl | Loops (for, foreach, while, do…while, until, Nested loops)

Last Updated : 20 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Looping in programming languages is a feature which facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Perl provides the different types of loop to handle the condition based situation in the program. The loops in Perl are : 
 

for Loop

“for” loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
Syntax:
 

for (init statement; condition; increment/decrement ) 
{
    # Code to be Executed
}

Flow Chart:
 

A for loop works on a predefined flow of control. The flow of control can be determined by the following :
 

  • init statement: This is the first statement which is executed. In this step, we initialize a variable which controls the loop.
  • condition: In this step, the given condition is evaluated and the for loop runs if it is True. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
  • Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.
  • increment/decrement: The loop control variable is changed here (incremented or decremented) for updating the variable for next iteration.
  • Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.

Example : 
 

Perl




# Perl program to illustrate
# the for loop
 
# for loop
for ($count = 1 ; $count <= 3 ; $count++)
{
    print "GeeksForGeeks\n"
}


Output: 
 

GeeksForGeeks
GeeksForGeeks
GeeksForGeeks

For those who are not fond of using ++ we can also do the following, it will produce the same output.

Perl




#!/usr/bin/perl
 
# Perl program to illustrate
# the for loop
 
# for loop
for ($count = 1 ; $count <= 3 ; $count+=1)
{
    print("GeeksForGeeks\n");
}


Output – 

GeeksForGeeks
GeeksForGeeks
GeeksForGeeks

foreach Loop

A foreach loop is used to iterate over a list and the variable holds the value of the elements of the list one at a time. It is majorly used when we have a set of data in a list and we want to iterate over the elements of the list instead of iterating over its range. The process of iteration of each element is done automatically by the loop.
Syntax: 
 

foreach variable 
{
    # Code to be Executed
}

Flow Chart:
 

Example:
 

Perl




# Perl program to illustrate
# the foreach loop
 
# Array
@data = ('GEEKS', 'FOR', 'GEEKS');
 
# foreach loop
foreach $word (@data)
{
    print $word
}


Output: 
 

GEEKSFORGEEKS

Another better way to print with spacing –

Perl




#!/usr/bin/perl
 
@data = ('GEEKS', 'FOR', 'GEEKS');
  
# foreach loop
foreach $word (@data)
{
    print("$word\n");
}


Output – 

GEEKS
FOR
GEEKS

 

while Loop

A while loop generally takes an expression in parenthesis. If the expression is True then the code within the body of while loop is executed. A while loop is used when we don’t know the number of times we want the loop to be executed however we know the termination condition of the loop. It is also known as a entry controlled loop as the condition is checked before executing the loop. The while loop can be thought of as a repeating if statement.
Syntax :
 

while (condition)
{
    # Code to be executed
}

Flow Chart:
 

while_loop_perl

Example : 
 

Perl




# Perl program to illustrate
# the while loop
 
# while loop
$count = 3;
while ($count >= 0)
{
    $count = $count - 1;
    print "GeeksForGeeks\n";
}


Output: 
 

GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks

We can also use the decrement operator to get the same output.

Perl




#!/usr/bin/perl
# Perl program to illustrate
# the while loop
 
# while loop
$count = 3;
while ($count >= 0)
{
    $count--;
    print("GeeksForGeeks\n");
}


Output – 

GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks

Infinite While Loop: While loop can execute infinite times which means there is no terminating condition for this loop. In other words, we can say there are some conditions which always remain true, which causes while loop to execute infinite times or we can say it never terminates. 
 

  • Example: Below program will print the specified statement infinite time and also give the runtime error as Output Limit Exceeded on online IDE
     

Perl




# Perl program to illustrate
# the infinite while loop
 
# infinite while loop
# containing condition 1
# which is always true
while(1)
{
    print "Infinite While Loop\n";
}


  • Output: 
     
Infinite While Loop
Infinite While Loop
Infinite While Loop
Infinite While Loop
.
.
.
.

 

do…. while loop

A do..while loop is almost same as a while loop. The only difference is that do..while loop runs at least one time. The condition is checked after the first execution. A do..while loop is used when we want the loop to run at least one time. It is also known as exit controlled loop as the condition is checked after executing the loop.
Syntax: 
 

do {

    # statements to be Executed

} while(condition);

Flow Chart: 
 

do-while

Example : 
 

Perl




# Perl program to illustrate
# do..while Loop
 
$a = 10;
 
# do..While loop
do {
 
    print "$a ";
    $a = $a - 1;
} while ($a > 0);


Output: 
 

10 9 8 7 6 5 4 3 2 1

 

until loop

until loop is the opposite of while loop. It takes a condition in the parenthesis and it only runs until the condition is false. Basically, it repeats an instruction or set of instruction until the condition is FALSE. It is also entry controller loop i.e. first the condition is checked then set of instructions inside a block is executed.
Syntax:
 

until (condition) 
{
   # Statements to be executed
}

Flow Chart:
 

until_loop_perl

Example : 
 

Perl




# Perl program to illustrate until Loop
 
$a = 10;
 
# until loop
until ($a < 1)
{
    print "$a ";
    $a = $a - 1;
}


Output: 
 

10 9 8 7 6 5 4 3 2 1

 

Nested Loops

A nested loop is a loop inside a loop. Nested loops are also supported by Perl Programming. And all above-discussed loops can be nested.
Syntax for different nested loops in Perl:
 

  • Nested for loop 
     
for (init statement; condition; increment/decrement ) 
{
    for (init statement; condition; increment/decrement ) 
    {
         # Code to be Executed
    }
}
  •  
  • Nested foreach loop 
     
foreach variable_1 (@array_1) {

    foreach variable_2 (@array_2) 
   {

       # Code to be Executed
   } 
}
  •  
  • Nested while loop 
     
while (condition)
{
    while (condition)
    {
        # Code to be Executed
    }
}
  •  
  • Nested do..while loop 
     
do{
    do{

        # Code to be Executed

       }while(condition);

}while(condition);
  • Nested until loop 
     
until (condition) {

    until (condition) 
    {
       # Code to be Executed
    }
}
  •  

Example : 
 

Perl




# Perl program to illustrate
# nested while Loop
 
$a = 5;
$b = 0;
 
# outer while loop
while ($a < 7)
{
   $b = 0;
    
   # inner while loop
   while ( $b <7 )
   {
      print "value of a = $a, b = $b\n";
      $b = $b + 1;
   }
    
   $a = $a + 1;
   print "Value of a = $a\n\n";
}


Output: 
 

value of a = 5, b = 0
value of a = 5, b = 1
value of a = 5, b = 2
value of a = 5, b = 3
value of a = 5, b = 4
value of a = 5, b = 5
value of a = 5, b = 6
Value of a = 6

value of a = 6, b = 0
value of a = 6, b = 1
value of a = 6, b = 2
value of a = 6, b = 3
value of a = 6, b = 4
value of a = 6, b = 5
value of a = 6, b = 6
Value of a = 7

 



Previous Article
Next Article

Similar Reads

Perl | Basic Syntax of a Perl Program
Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar
10 min read
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Decision Making in programming is similar to decision making in real life. In programming, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance
6 min read
while loop in Perl
A while loop in Perl generally takes an expression in parenthesis. If the expression is True then the code within the body of while loop is executed. A while loop is used when we don't know the number of times we want the loop to be executed however we know the termination condition of the loop. It is also known as an entry controlled loop as the c
2 min read
Perl | chomp() Function
The chomp() function in Perl is used to remove the last trailing newline from the input string. Syntax: chomp(String) Parameters: String : Input String whose trailing newline is to be removed Returns: the total number of trailing newlines removed from all its arguments Example 1: C/C++ Code #!/usr/bin/perl # Initialising a string $string = &amp;quo
2 min read
Perl | Backtracking in Regular Expression
In Perl, a Regular expression(a.k.a regexes or regexps or REs) is a way of describing a set of strings without having to list all strings in your program or simply we can say that it is a sequence of characters that are used for pattern matching. In Perl, regular expressions have different uses: Firstly, they are used in conditionals to determine w
3 min read
Perl | Searching in a File using regex
Prerequisite: Perl | Regular Expressions Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to host language and are not the same as in PHP, Python, etc. Sometimes these are termed as "Perl 5 Compatible Regular Expressions". To use the Regex, Bindi
6 min read
Perl | Operators | Set - 1
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Operators Can be categorized based upon their different functionality: Arithmetic OperatorsRelat
12 min read
Perl | lt operator
'lt' operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise less than the string to its right. Syntax: String1 lt String2 Returns: 1 if left argument is less than the right argument Example 1: #!/usr/local/bin/perl # Initializing Strin
1 min read
Perl | chop() Function
The chop() function in Perl is used to remove the last character from the input string. Syntax: chop(String) Parameters: String : It is the input string whose last characters are removed. Returns: the last removed character. Example 1: #!/usr/bin/perl # Initialising a string $string = &quot;GfG is a computer science portal&quot;; # Calling the chop
1 min read
Perl | rename() Function
rename() function in Perl renames the old name of a file to a new name as given by the user. Syntax: rename(old_file_path, new_file_path) Parameters: old_file_path: path of the old file along with its name new_file_path: path of the new file along with its name Returns 0 on failure and 1 on success Example: #!/usr/bin/perl -w # Calling the rename()
1 min read
Perl | Subroutines or Functions
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in s
2 min read
Perl | Comparing Scalars
Prerequisite: Scalars in Perl Perl has two types of comparison operator sets. Just like other mathematical operators, instead of performing operations, these operators compare scalars. There are two types of sets of Perl comparison operators. One is for numeric scalar values and one is for string scalar values. Both the types are illustrated in bel
6 min read
Perl | String functions (length, lc, uc, index, rindex)
String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follows: length() lc() uc() index() rindex() length(): T
4 min read
Perl | Arrays
In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Example: @number = (50, 70, 46); @names = ("Geeks", "For", "Geeks"); Array Creation: In Perl programming ever
6 min read
Perl | Data Types
Data types specify the type of data that a valid Perl variable can hold. Perl is a loosely typed language. There is no need to specify a type for the data while using in the Perl program. The Perl interpreter will choose the type based on the context of the data itself. There are 3 data types in Perl as follows: ScalarsArraysHashes(Associative Arra
3 min read
Perl | String Operators
Operators are the foundation of any programming language. Thus, the functionality of Perl programming language is incomplete without the use of operators. A user can define operators as symbols that help to perform specific mathematical and logical computations on operands. String are scalar variables and start with ($) sign in Perl. The String is
4 min read
Perl | Hashes
Set of key/value pair is called a Hash. Each key in a hash structure are unique and of type strings. The values associated with these keys are scalar. These values can either be a number, string or a reference. A Hash is declared using my keyword. The variable name is preceded by the dollar sign($)followed by key under curly braces and the value as
5 min read
Perl | Regular Expressions
Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“. To use the Regex, Binding operators like ‘=~‘(Regex Operator) and
2 min read
Perl | Regex Cheat Sheet
Regex or Regular Expressions are an important part of Perl Programming. It is used for searching the specified text pattern. In this, set of characters together form the search pattern. It is also known as regexp. When user learns regular expression then there might be a need for quick look of those concepts which he didn't use often. So to provide
6 min read
Introduction to Perl
Perl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most used expansion is "Practical Extraction and Reporting Language". Some of the programmers also refer Perl as the "Pathologically Eclectic Rubbish Lister" Or "Prac
9 min read
Perl | Regex Character Classes
Character classes are used to match the string of characters. These classes let the user match any range of characters, which user don’t know in advance. Set of characters that to be matched is always written between the square bracket []. A character class will always match exactly for one character. If match not found then the whole regex matchin
3 min read
Perl | Special Character Classes in Regular Expressions
There are many different character classes implemented in Perl and some of them used so frequently that a special sequence is created for them. The aim of creating a special sequence is to make the code more readable and shorter. The Special Character Classes in Perl are as follows: Digit \d[0-9]: The \d is used to match any digit character and its
4 min read
Perl | Subroutines or Functions | Set - 2
Prerequisite: Subroutines or Functions in Perl A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In this article we will di
4 min read
Perl | Operators | Set - 2
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Some of the operators already discussed in Perl Operators Set - 1. Remaining operators will be d
7 min read
Perl | qw Operator
The qw operator in Perl is used to extract each element of the given string as it is in an array of elements in single-quote ( ' ' ). This function stands for quote word because it considers each word of the given string as it is quoted like qw(Geeks for Geeks) is equivalent to ('Geeks', 'for', 'Geeks'). This qw() uses parentheses so it seems like
2 min read
Perl | Reverse an array
Reverse an array or string in Perl. Iterative Way: Iterate over the array from 0 to mid of array. Swap the arr[i] element with arr[size-i] element. #Perl code to reverse an array iteratively #declaring an array of integers @arr = (2, 3, 4, 5, 6, 7); # Store length on array in $n variable $n = $#arr; #Print the original array print &quot;The origina
2 min read
Packages in Perl
A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension .pm. Two different modules may contain a variable or a function of the same name. Any variable which is not contained in any package belongs to the main package. There
4 min read
Perl | Scope of Variables
The scope of a variable is the part of the program where the variable is accessible. A scope is also termed as the visibility of the variables in a program. In Perl, we can declare either Global variables or Private variables. Private variables are also known as lexical variables. Scope of Global Variables Global variables can be used inside any fu
6 min read
Perl | References
In Perl, we use variables to access data stored in a memory location(all data and functions are stored in memory). Variables are assigned with data values that are used in various operations. Perl Reference is a way to access the same data but with a different variable. A reference in Perl is a scalar data type that holds the location of another va
4 min read
Perl | Math::BigInt-&gt;digit() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. digit() method of Math::BigInt module is used to get nth digit of the given number counting from right. To get the digit from the left side we need to specify n as negative. Syntax: Math::BigInt-&gt;digit($n) Paramete
3 min read
Article Tags :