A BLOCK
in Perl is a collection of statements enclosed inside curly brackets.
A BLOCK
can be labeled or unlabeled. Regardless, it is treated as a loop that executes once.
LABEL: {
statement1
statement2
.
.
.
statementN
}
Here,
statement1
,statement2
andstatementN
are placeholders for actual Perl statements.
There are several use cases of the basic BLOCK
in Perl
. This shot looks at a few of them.
Switch
exampleThe following example uses the BLOCK
as a switch
construct.
$x = 10;SWITCH: {if ($x > 10) { print "Greater than 10"; last SWITCH }if ($x < 10) { print "Less than 10"; last SWITCH }if ($x == 10) { print "Equal to 10"; last SWITCH }}
In the example above, the variable x
is initialized with the value 10
. The SWITCH
BLOCK
contains three if
statements that compare the value of x
with 10
.
If the comparison yields true
, then the relevant text is output on the screen and the SWITCH
BLOCK
is exited.
Loop
exampleThe following example uses the BLOCK
as a loop
.
$i = 0;LOOP: {print "Loop iteration $i\n";$i = $i + 1;if ($i < 5) { redo; }}
In the example above, the variable i
is initialized with the value 0
, which will be used to control the number of loop iterations.
Inside the LOOP
BLOCK
, the value of i
is printed and then incremented. If the value of i
is less than 5
, then redo
is used to re-execute the LOOP
BLOCK
.