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++) ## More complex for loop for ( control variable initialization ; loop continuation ; increment/decrement of the control variable ) |
Foreach Statement | @word = qw( hello world goodbye and goodnight ); foreach $word (@word) ## More complex foreach loop |
Do Statement | $count = 1; Note: the do statement will execute at least once |
Last Statement | $count = 1; |
Next statement | $count = 1; while ( $count <= 10 ) { next if ($count++ % 2 == 0); print ("Count: $count \n"); } |
Redo Statement | $count = 1; 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++ ) 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"); Note: this code will result in a infinite loop, told you so never ever use goto statements |