4.1 Blocks
The first tool that you need to begin to use control structures is the
ability to write code "blocks". A block of code could be any of the code
examples that we have seen thus far. The only difference is, to make them a
block, we would surround them with {}
.
use strict;
{
my $var;
Statement;
Statement;
Statement;
}
Anything that looks like that is a block. Blocks are very simple, and are
much like code blocks in languages like C, C++, and Java. However, in Perl,
code blocks are decoupled from any particular control structure. The above
code example is a valid piece of Perl code that can appear just about
anywhere in a Perl program. Of course, it is only particularly useful for
those functions and structures that use blocks.
Note that any variable declared in the block (in the example,
$var
) lives only until the end of that block. With variables
declared my
, normal lexical scoping that you are familiar with in
C, C++, or Java applies.