Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

perl
blocks
loop
switch
communitycreator

What are basic BLOCKs in Perl 5.3.4?

Hammad Nasir

Overview

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.

Syntax


LABEL: {
  statement1
  statement2
  .
  .
  .
  statementN
}

Here, statement1, statement2 and statementN are placeholders for actual Perl statements.

Code

There are several use cases of the basic BLOCK in Perl. This shot looks at a few of them.

Switch example

The 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 }
}

Explanation

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 example

The following example uses the BLOCK as a loop.

$i = 0;

LOOP: {
  print "Loop iteration $i\n";
  $i = $i + 1;
  if ($i < 5) { redo; }
}

Explanation

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.

RELATED TAGS

perl
blocks
loop
switch
communitycreator
RELATED COURSES

View all Courses

Keep Exploring