More Perl Control Structures

This web page discusses the following

Single-Line Conditional Statements

Single-Line Conditional Statement print ("Hello World!\n") if ( $var == 0 );
print ("Hello World!\n") unless( $var != 0 );
print ("Hello World!\n") while ( $var-- > 0 );
print ("Hello World!\n") until ( $var-- == 0 );

die( "ERROR opening file\n") unless (open(INFILE, "employees.dat"));

Looping Control Statements

For statement

for ($count = 1; $count <= 10; $count++)
{
   print ("Count: $count");
}

## More complex for loop
for ($line = <STDN>, $count = 1; $count <= 3; $line = <STDIN>, $count++)
{
   print ($line);
}

for ( control variable initialization ; loop continuation ; increment/decrement of the control variable )

Foreach Statement

@word = qw( hello world goodbye and goodnight );

foreach $word (@word)
{
   print ("The word is $word\n");
}

## More complex foreach loop
$line = "This is a lovely day to be fishing";

foreach $word (reverse sort split(/[ ]+/, $line))
{
   print ("$word ");
}    

Do Statement

$count = 1;
do {
  $count++;
  print ("$count\n");
} while ($count < 10);

Note: the do statement will execute at least once

Last Statement

$count = 1;
while ( $count <= 10 )
{
   print ("Count: $count \n");
   last if ($count >= 5);          // break out of the while loop if $count is 5
   $count++;
}

Next statement $count = 1;
while ( $count <= 10 )
{
   next if ($count++ % 2 == 0);
   print ("Count: $count \n");
}
Redo Statement

$count = 1;
while ( $count <= 10 )
{
  redo if ($count++ % 2 == 0);   // because of this statement goes beyond 10
  print ("Count: $count \n");
}

Note: notice that the loop continues beyond the while loops condition because of the redo statement

Labeled Blocks

STOP: for ( $row = 1; $row <= 10; $row++ )
      {
         for ( $column = 1; $column <= 5; $column++ )
         {
            print ("Column : $column Row: $row\n");
            last STOP if ( $row == 5 );
         }
      }

Note: you can also use redo and next with labeled blocks

Continue block $count = 1;
while ( $count <= 10 )
{
   print ("Count: $count\n");
}
continue
{
   $count++;
}

Goto Statement

For completeness I have included the goto statement but you should never ever use this statement

Goto statement

JUMPHERE: print ("Do not use the goto statement\n");
print ("This statement is below the goto statement\n");
goto JUMPHERE;

Note: this code will result in a infinite loop, told you so never ever use goto statements