Perl while Statement



Perl while Menu:

1. The syntax forms
    1.1. General while statement
        1.1.1. The conditional expression is false initially
        1.1.2. An infinite loop
        1.1.3. Using my declaration in the conditional expression
        1.1.4. How to simulate a for statement using the while loop
        1.1.5. Using while with the diamond operator <>
        1.1.6. Control the flow of a while loop with next, last and redo
        1.1.7. How to print a hash using each and while
    1.2. while used as a modifier
2. More examples



The while statement is one of the basic looping statements available in Perl language. In this free tutorial I’ll show you the main syntax forms of this statement and a few examples about how to use it in your Perl scripts.

The while loop repeats the execution of a block as long as a certain condition is evaluated true. Inside the block of the while statement you can use any of the three looping controls: last, next or redo. In this case it could be useful to precede the while statement with an optional label that identifies the block. Please remember that any block is a piece of code enclosed in a pair of curly braces.

After the loop block, you can use the continue clause if you need to specify some additional statements to be executed after the current iteration of the block.

The Perl while statement can be used with a do block, too. An alternative to the while statement is the until statement, which executes the block only as long as the condition is evaluated false.

1. The syntax forms


At this point you may be wondering how to use it in your code. To begin with, there are two syntax forms for the Perl while statement: general while statement and while used as a modifier. In the following, I'll describe both cases.

    1.1. General while statement


LABEL while (EXPR) BLOCK continue BLOCK

This first form is the general syntax of the Perl while statement. Here LABEL is optional and if present, it consists of an identifier, usually in uppercase, followed by a colon. The label can be used as an anchor for jumping to from within the block, if you’ll use one of the three looping controls: next, last or redo (you can use the goto statement too, but we don’t recommend it).

EXPR is a boolean conditional expression that it will be evaluated before the execution of the block. The Perl while statement will repeatedly execute the block as long as EXPR is true.

The continue block is executed before the successive reevaluations of the test condition, excepting the case when the main block is exited by the last loop control. It provides a block of statements to be executed after the current iteration is terminated.


       1.1.1. The conditional expression is false initially


If initially the expression is false, the Perl while loop will not be executed at all, and the program will skip to the next statement after the block. Please consider the following short snippet code:

$day = "Monday";
while ($day eq "Sunday") {
  print "It's Sunday\n";
} 
print "It's Monday\n";
# displays It’s Monday

In the above code, the expression will be evaluated false, so the script program will continue with the statement that follows the while block.

       1.1.2. An infinite loop


You can very easily generate an infinite loop if the expression is always true, as shown in next lines of code:

while(1) {
  $k++;
}
# the next statement will never be reached:
$k = 0;

If you will test this code from a command prompt on a windows platform, you’ll need to type Ctrl/C to end the program (Ctrl/Z in Linux).

If you want to exit from an infinite loop, you can use the last loop control, as shown in the next example:

$k = 0;
while(1) {
  last if $k == 1000;  
  $k++;
}
print "k = $k\n";
# it displays k = 1000;

       1.1.3. Using my declaration in the conditional expression


A variable declared with my in the test condition of a Perl while loop is visible in the main block of the Perl while statement, but it extends throughout the rest of the loop construction, including the continue block, like in the following example:

# initialize a hash (associative array)
%numbers = (1 => 'one ', 2 => 'two ',
            3 => ' three', 4 => ' four');
while(my $key = each %numbers) {
  $numbers{$key} = $key * 10;;
}
continue {
  print "Key: $key, Value: $numbers{$key}\n";
}

This code will output:

Key: 4, Value: 40
Key: 1, Value: 10
Key: 3, Value: 30
Key: 2, Value: 20

We modified the value of each key in the main block of the Perl while statement and after that we print the (key value) pairs of the hash structure in the continue block. Note that the elements of the hash structure are not printed in the natural order I initialized the hash because Perl has its internal order in which it stores the elements. If you want to sort the elements by key or by values, see Sort or order a hash.

       1.1.4. How to simulate a for statement using the while loop


If you want, you can write your own for statement using the Perl while statement, as shown in the following example:

# initialize a square numbers array
@sqNoArray = ();
FOR: {
  my $k = 1; # the initialization
  while($k <= 10)  # the condition
  {
    # append an element to the array
    push(@sqNoArray, $k**2);
  }
  continue { $k++; } # the re-initialization
} # end of FOR block

# print the @sqNoArray
print "@sqNoArray\n";
# output: 1 4 9 16 25 36 49 64 81 100

As you can see in the above example, we specified all the three expressions used in a for statement: the initialization, the condition and the re-initialization. Please note that the re-initialization expression was implemented as a continue block that is always executed before the Perl while test condition is reevaluated. We used the my declaration to limit the scope of the $k variable inside the FOR block. This example will generate an array with the first 10 square numbers.


       1.1.5. Using while with the diamond operator <>


The next example illustrates one of the most commonly way to use Perl while statement in connection with the diamond operator <>:

#initialize an array
@colors = ();
while(<STDIN>) {
  chomp;
  push(@colors, $_);    
}
print "Colors: @colors\n";

We want to read some color names from keyboard (one color name on a line) and store them in an array. This code will read from STDIN one line at a time; each line is assigned in turn to $_; the chomp function will remove the trailing newline from $_; after that, the value stored in $_ will be appended to the @colors array. The while iterations will stop when the EOF (typing Ctrl/Z in Windows, Ctrl/d in Linux) will be reached.

You can rewrite the above snippet code without using the special variable $_, in the following way:

#initialize an array
@colors = ();
while($line = <>) {
  chomp $line;
  push(@colors, $line);    
}
print "Colors: @colors\n";

The difference from the previous code is that the lines of text will be read one by one in the variable $line and the chomp function will be called against the $line variable. In the same time we didn’t specify any file handle for the diamond operator and in this case Perl interpreter will examine the special variable @ARGV. If there are no elements in the @ARGV array, the diamond operator <> will read from STDIN (i.e. the keyboard or a redirected file).

A possible output after running any of the codes above might be:

red
yellow
green
Ctrl/Z 
Colors: red yellow green

After you finished entering the colors (each one on a different line) you must type Ctrl/z in Windows or Ctrl/d in Linux to mark the end of the text file.

At this point you may wonder how to use Perl while statement with <> when the @ARGV array is not empty. When you are running a Perl script, the elements of the @ARGV array will be added from the command line. The next example is meant to be run for a Windows platform and from the command line. On my computer Perl is installed on the C:\ drive. Please take a look at the following table columns:

 Colors.pl   Colors1   Colors2 
 while(<>) { print(); }  red white
  green blue
    yellow

I created three files: Colors.pl that represents the name of my script and Colors1, Colors2 with the lines indicated in the above table. After I created the three files in the \bin directory of Perl, I ran the Colors.pl script from the command line and I’ve got the following output:

C:\Perl\bin\perl Colors.pl Colors1 Colors2
red
green

white
blue
yellow


That’s what the Colors.pl script does:
  • the @ARGV array contains two elements, respectively the file names Colors1 and Colors2
  • the diamond operator from the while statement will start reading all the lines from Colors1 file and it will continue with Colors2 file. Each line read from the files will be printed. After finishing reading the files, the Perl while loop will end.
You can also do this by initializing the @ARGV array inside your Perl script, like in the next example:

@ARGV = qw(Colors1 Colors2);
while(<>) { print(); }

You’ll get the same output like in the previous example.


       1.1.6. Control the flow of a while loop with next, last and redo


Please take a look at the following script example:

$count = 0;
while($count++ < 3) {
  chomp(my $line = <STDIN>);
  last if $line =~ /quit/;
  next if $line =~ /while|until/i;
  redo;
}
# end of the loop
print "Count = ", --$count, "\n";

Here is an output to illustrate how the above code works:

this is while Perl statement
if else
until statement
unless - this is not a loop
something else
quit
Count = 2

What are we doing in this snippet code?
  • well, in the first line of code we initialize the $count scalar variable with 0 – we are using this variable to count the number of lines read from STDIN that match the while or until words
  • in the condition expression of the Perl while statement we increment the $count variable and we’ll leave the loop after the $count value becomes greater than or equal to 3
  • in the line three of code we read a line of text from STDIN, we discard the trailing newline and we store the result in the $line scalar variable
  • we use the last looping control to leave the loop if we read 'quit' from STDIN
  • if we case insensitively match the word while or until in the $line variable, we use the next looping control to reiterate the loop by skipping the remainder of the code block
  • if we don’t match neither while nor until, we’ll reexecute the code block without the reevaluating of the test condition of the Perl while statement
  • (redo looping control)
  • after ending the loop, we’ll print the $count scalar variable value

       1.1.7. How to print a hash using each and while


To see this topic click here to watch a video on youtube where you'll find a complete example.


    1.2. while used as a modifier


STATEMENT while (EXPR)

This second form uses Perl while as a modifier of a statement. It is a quite simple form, you can see an example next:

$count = 0;
print $count, " " while ++$count <= 10;
print "\n"; 
# it displays 1 2 3 4 5 6 7 8 9 10


A-N-Y-O-N-E Can Learn and Master Perl!
And That Includes YOU!


Check these how-to tutorial eBooks (PDF format):


Table of Contents:

A Perl Script
Install Perl
Running Perl
Perl Data Types
Perl Variables
Perl Operators
Perl Lists
Perl Arrays
    Array Size
    Array Length
Perl Hashes
Perl Statements
    Perl if
    Perl unless
    Perl switch
    Perl while (more)
    Perl do-while
    Perl until
    Perl do-until
    Perl for
    Perl foreach
Built-in Perl Functions
    Functions by Category
        String Functions
        Regular Expressions and Pattern Matching
        List Functions
        Array Functions
        Hash Functions
        Miscellaneous Functions
    Functions in alphabetical order
        chomp
        chop
        chr
        crypt
        defined
        delete
        each
        exists
        grep
        hex
        index
        join
        keys
        lc
        lcfirst
        length
        map
        oct
        ord
        pack
        pop
        push
        q
        qq
        qw
        reverse
        rindex
        scalar
        shift
        sort
        splice
        split
        sprintf
        substr
        tr
        uc
        ucfirst
        undef
        unpack
        unshift
        values

return to Perl Basics



Would you like to create your own website like this one?
Hit the Alarm Clock!

Site Build It!