Complex Statements and Blocks

Conditionals and loops are sometimes called complex statements. That's because instead of being a single statement like $x = 5 or $array[5] = "fifth" ending with a semicolon, conditionals and loops tend to be more, well, complex. Probably the biggest difference between simple and complex statements, however, is that the latter operate on chunks of Perl code called blocks.

A block is, simply, a group of any Perl statements surrounded by curly braces ({}). Inside the block, you can include other statements, other blocks, or anything that can appear outside the block. As with statements in a script, too, the statements inside the block are executed in order. For example, here are two blocks, one that is associated with a while loop, and one inside it that is associated with an if conditional:

while (test) { # start of while block
   statement;
						statement;
   if (test) { # start of if block
      statement;
   } # end of if block
   # ... more statements
} # end of while loop

Note that each closing curly brace ends the nearest enclosing blockā€”the indenting doesn't matter to Perl. In larger scripts, a block might go on for lines and lines and you can easily forget where a closing } is supposed to match to. In this case, an indenting style can really help you figure out where your blocks begin and end. When in doubt, add a comment.

Blocks that are used outside the context of a conditional or a loop are called bare blocks, and the statements inside them execute only once. Bare blocks have several uses, particularly when they have labels (more about labels later in this chapter), but for now we'll focus on blocks that are attached to complex statements.

One other feature of blocks is that the last statement in the block doesn't require a semicolon. If it's the only statement in the block, it also doesn't require a semicolon. However, it's probably a good idea to get used to using it anyhow; if you add other statements to that block later, Perl will complain that you forgot the semicolon.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.247.166