WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Perl · Basic · question 12 of 100

Explain the basic looping constructs in Perl (e.g., for, foreach, while, until).?

📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

Perl provides four main looping constructs: ‘for‘, ‘foreach‘, ‘while‘, and ‘until‘.

1. The ‘for‘ loop executes a block of code for a specified number of times or for a range of values. The syntax is as follows:

for (initialization; condition; increment) {
    # code to be executed
}

Here, ‘initialization‘ is used to initialize the loop variable, ‘condition‘ is checked before each iteration, and ‘increment‘ is executed at the end of each iteration.

Example:

for ($i=0; $i<5; $i++) {
    print "$in";
}

Output:

0
1
2
3
4

2. The ‘foreach‘ loop iterates over a list of values and executes the block of code once for each item in the list. The syntax is as follows:

foreach $variable (list) {
    # code to be executed
}

Example:

@list = (1, 2, 3, 4, 5);
foreach $num (@list) {
    print "$numn";
}

Output:

1
2
3
4
5

3. The ‘while‘ loop executes the block of code repeatedly as long as the specified condition is true. The syntax is as follows:

while (condition) {
    # code to be executed
}

Example:

$i = 1;
while ($i <= 5) {
    print "$in";
    $i++;
}

Output:

1
2
3
4
5

4. The ‘until‘ loop is similar to the ‘while‘ loop, except that it executes the block of code repeatedly until the specified condition is true. The syntax is as follows:

until (condition) {
    # code to be executed
}

Example:

$i = 1;
until ($i > 5) {
    print "$in";
    $i++;
}

Output:

1
2
3
4
5

It’s important to note that Perl also has the ‘do...while‘ and ‘do...until‘ constructs which are similar to ‘while‘ and ‘until‘, but the condition is checked at the end of the loop instead of the beginning.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Perl interview — then scores it.
📞 Practice Perl — free 15 min
📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

All 100 Perl questions · All topics