What is a block?

The simplest block is a single statement, for instance:

print "Hello, world!\n";

Sometimes you'll want several statements to be grouped together logically. That's what we call a block. A block can be executed either in response to some condition being met, or as an independent chunk of code that's given a name.

Blocks always have curly brackets ( { and } ) around them. In C and Java, curly brackets are optional in some cases - not so in Perl.

{
        $fruit = "apple";
        $howmany = 32;
        print "I'd like to buy $howmany $fruit" . "s.\n";
}

You'll notice that the body of the block is indented from the brackets; this is to improve readability. Make a habit of doing it.

The Camel book refers to blocks with curly braces around them as BLOCKs (in capitals). It discusses them on page 97.

Scope

Something that needs mentioning again at this point is the concept of variable scoping. You will recall that we use the my function to declare variables when we're using the strict pragma. The my also scopes the variables so that they are local to the current block

#!/usr/bin/perl -w

use strict;

my $a = "foo";

{                               # start a new block
        my $a = "bar";
        print "$a\n";           # prints bar
}

print $a;                       # prints foo

Now, onto the situations in which we'll encounter blocks.