Perl Statements

A Perl script consists of a series of statements and comments. Each statement is a command that is recognized by the Perl interpreter and executed. Statements are terminated by the semicolon character (;). They are also usually separated by a newline character to enhance readability.

A comment begins with the # sign and can appear anywhere. Everything from the # to the end of the line is ignored by the Perl interpreter. Commonly used for human-readable notes.

Some Statements

$sum = 2 + 2; # this is a statement

$f = <STDIN>; $g = $f++;  # these are two statements

$g = $f
  /
  $sum;        # this is one statement, spread across 3 lines

The Perl interpreter will start at the top of the script and execute all the statements, in order from top to bottom, until it reaches the end of the script. This execution order can be modified by loops and control structures.

Blocks

It is common to group statements into blocks using curly braces. You can execute the entire block conditionally, or turn it into a subroutine that can be called from many different places.

Example blocks:
{  # block starts
  my $EcoRI = 'GAATTC';
  my $sequence = <STDIN>;
  print "Sequence contains an EcoRI site" if $sequence=~/$EcoRI/;
}  # block ends

my $sequence2 = <STDIN>;
if (length($sequence) < 100) {  # another block starts
  print "Sequence is too small. Throw it back\n";
  exit 0;
} # and ends

foreach $sequence (@sequences) {  # another block
  print "sequence length = ",length($sequence),"\n";
}

Labeled Blocks

You can also attach a label to a block of statements like this:
READ_SEQUENCE: {
  $sequence = <STDIN>
  print "length = ",length($sequence),"\n";
}
This is sometimes useful for controlling nested loops; we discuss it later.


<< Previous
Contents >> Next >>

Lincoln D. Stein, lstein@cshl.org
Cold Spring Harbor Laboratory
Last modified: Sun Oct 10 13:43:20 EDT 1999