Perl Programming   «Prev  Next»
Lesson 8Perl general syntax and structure
ObjectiveBasic syntax and structure of Perl program

Perl General Syntax and Structure

Learn the basic syntax and structure of a Perl program. Perl is structured to allow as great a variety of syntactic constructions as possible.
It is not a line-oriented language. Perl statements are terminated by a semicolon (;) character.
(The semicolon is optional at the end of a block, but we'll cover blocks later.)
So this:

$x = 1;
print "$x\n";

is syntactically equivalent to this:
$x = 1; 
print "$x\n";

There are two structural elements common to Perl scripts: 1) Comments and 2) Shebang
Comments

Perl Shebang line

If you have looked at Perl scripts, then you have seen that they most always start with
    
#!/usr/bin/perl
According to a Unix convention when the first two bytes of a file are #! (23H, 21H), whatever is in the remainder of that first line is taken to be the command line for the shell to run the script with. Therefore, it is customary to start every Perl program with a line like this:

#!/usr/bin/perl

Actual Path

Be sure to use the actual path to the perl program on your system (/usr/bin/perl is common for Perl 5).
This is often called the shebang line because of what it sounds like when you say "hash-bang" for the millionth time.

The -w switch


You can put command-line switches in the shebang line, and they will be passed to the perl program as well.
This command is going to occur frequently.

#!/usr/bin/perl -w

The -w switch tells perl to warn you about common misuses of variables and subroutines. It is useful, not only for beginners, but to catch the sorts of errors that we all make from time to time.
Even on operating systems that do not use the shebang convention, this line is still useful in your Perl programs. The perl interpreter will use it anyway and apply whatever command-line switches you have included.

Perl is considered by some to have convoluted and confusing syntax; others consider this same syntax to be compact, flexible, and elegant. Though the language has most of the features one would expect in a full service programming notation, Perl has become well known for its capabilities in a few areas where it exceeds the capabilities of most other languages. These include
  1. String manipulation
  2. File handling
  3. Regular expressions and pattern matching
  4. Flexible arrays (hashes, or associative arrays)
In the next lesson, a test bed will be created in which you can experiment with the code you are going to encounter throughout this course.

Perl 6