The Perl until loop examples and syntax

Perl until loop FAQ: Can you share some examples of the Perl until loop syntax?

The Perl until loop is similar to the Perl while loop, but essentially does the opposite thing. Where the Perl while operator will run this loop forever:

while ('true')
{
  # do stuff here
}

the Perl until loop will never run this loop:

until ('true')
{
  # do stuff here
}

The Perl until loop never runs that block of code because the loop test condition is immediately true. So, where the while loop runs a loop as long as a condition is true, the Perl until loop runs until a condition is true.

(Also, for more information on why that statement in parentheses evaluates to true, see my Perl true and false tutorial.)

Another "Perl until" loop example

Here's a slightly more helpful "Perl until" example that shows how an until loop is typically used:

$i = 0;

until ($i++ > 5)
{
  print "i is $i\n";
}

That simple Perl until loop results in the following output:

i is 1
i is 2
i is 3
i is 4
i is 5
i is 6

As you can see, the until loop runs until the given condition evaluates to "true".

Perl until loop as an expression modifier

Oops, I thought I was finished, but then I remembered a very cool way to use the Perl until loop.

The cool thing I forgot is that you can use the Perl until operator as an expression modifier, like this:

print "Yo\n" until $i++ > 5;

An expression modifier lets you follow a normal expression with a modifier on the right hand side of your Perl statement, and it controls the execution of that expression. In this example, our output looks like this:

Yo
Yo
Yo
Yo
Yo
Yo

I really like this use of the Perl until loop, because it makes the code easy to read. You can easily read that sentence as "Print this string until the variable $i is greater than 5." It doesn't get much easier than that.

Perl until loop - summary

The Perl until loop is another nice tool to have in your Perl programming toolbox. Under the right circumstances it can make for a more readable Perl loop (and Perl code, in general), and I'm all for that.