Any simple statement can have one of four possible modifiers attached to them at the end. The modifiers cannot be appended to blocks, only to individual simple statements. The modifiers are given below.
if expression
unless expression
while expression
until expression
The keywords have the obvious meaning. We have an example of in Section 2.10. One example from this section is given below.
die $errorStmt if (($n < 0) or ($n =~ /[.]/));
We can write this statement also as the following if we want.
die $errorStmt unless (($n >= 0) or ($n !~ /[.]/));
Section 2.10 has several other usage of die. Two more are repeated below.
open (IN, $oldfilename) or die "Cannot open $oldfilename for reading: $!";
open (OUT, ">$newfilename") || die "Cannot open $newfilename for writing: $!";
These two can alternatively be written as the following.
die "Cannot open $oldfilename for reading: $!"
unless (not open (IN, $oldfilename));
die "Cannot open $newfilename for writing: $!"
unless (not open (OUT, ">$newfilename"));
The following program shows additional use of statement modifiers. The use of while and until modifiers is not really useful, but made up to illustrate the point.
Program 2.28
#!/usr/bin/perl
#whilemod.pl
$b = $a++ while ($a <= 100);
print "a = $a\tb=$b\n";
$b = ++$a while ($a <= 200);
print "a = $a\tb=$b\n";
$b = $a-- until ($a <= 50);
print "a = $a\tb=$b\n";
$b = --$a until ($a <= 0);
print "a = $a\tb=$b\n";
The modifiers used are while and until. The initial value of $a is 0. It is incremented to 101 and then printed. It is then incremented again to 201 and printed. Next, it is decremented using two statements with the until modifier. In every increment and decrement statement, $b is assigned. The output of the program is given below.
a = 101 b=100
a = 201 b=201
a = 50 b=51
a = 0 b=0
The first assignment statement with the while modifier increments $a after performing the assignment. Therefore, after the last iteration of the first statement, the value of $b is 100, the value of $a before the first increment. The second assignment statement with the while modifier assigns a value to $b before incrementing $a. $a-- returns the value for the assignment to $b and then decrements. --$a decrements the value of $a and then returns the value for assignment. Thus, placing ++ or -- before the name of the scalar variable causes incrementing or decrementing to happen first, then the value returned for use. The opposite happens if ++ or -- is placed after the variable.