How to create an infinite loop in Perl

There are several ways how you can create an infinite loop in Perl.

Use while

The first method through which you can create an infinite loop is to use cycle while. This loop is executed until the expression is true. As expressions to write a simple constant, which is true in this case the loop will run infinitely. Here is an example code:

#!/usr/bin/perl

while (1) {
    # some code
}

If you need to complete this cycle, then in the loop you need to perform last. Here's an example:

▶ Run
#!/usr/bin/perl

my $i = 0;
while (1) {
    print $i;
    last if $i > 2;
    $i++;
}

Note that to exit the loop keyword is used last, not returnand not break.

Use for

Here's how to write an infinite loop on the Perl programming language c using for:

#!/usr/bin/perl

for (;;) {
    # some code
}

After for 3 in brackets is the code snippet:

  • the initial value
  • check
  • change

Usually the body of the loop is performed if the test returns true. But if the check is missing, in this particular case, it turns infinite loop.

To exit this infinite loop you need to use last:

▶ Run
#!/usr/bin/perl

for (my $i = 0;;$i++) {
    print "$i";
    last if $i > 2;
}

Use until

Here's another way how you can create an infinite loop in Perl:

#!/usr/bin/perl

do {
    # some code
} until(0)

The code block executes until the condition in until is a lie.

In order to get out of this endless cycle, too, need to use the keyword last, but to make it work correctly you need to place all code an infinite loop in braces:

▶ Run
#!/usr/bin/perl

my $i = 0;

{
    do {
        print $i;
        last if $i > 2;
        $i++;
    } until(0)
}

Here is an example where we are trying to use last, but not the enclosed code brackets:

▶ Run
#!/usr/bin/perl

my $i = 0;

do {
    print $i;
    last if $i > 2;
    $i++;
} until(0)

If you run this code, it will error:

Can't "last" outside a loop block at script.pl line 7.
0123

Related topics

Other articles

Comments