Perl - Basic Syntax

Syntax of Perl Scripts

Perl syntax is very simple and flexible. It is based on the principle of forgiveness. Most languages have their own lunacies. Some need a bracket for parameters of a function, some don't. Some are hard on types. Some don't understand types... Perl takes care of all of these aspects. You may pass parameters in brackets if you like. But that is not required. If you care for it, the variables are typed else they are not. There is only aspects that Perl enforces - Curly Braces to mark blocks. Let's have a skyview of the Perl syntax.

Comments

The foremost in any syntax are the comments. In Perl, anything that follows a # is considered a comment. This may be the first character of a line or it could be midway. But anything between the # and the new line is a comment and the interpreter does not look at it.

The Semicolon

Every line of code in Perl must end with the ; That is defined as the end of a code line. A new line or any white space is redundant. A single line of code can span several lines of text and we can have several lines of code on one line of text.

Statements and Tokens

In Perl, all code consists of three components: The statement, the tokens and a return value. Every line of code is a function call (statement) with some parameters passed into it (tokens) and has a return value that may or may not be captured into a variable. The parameters may be passed in a bracket (comma separated) or without a bracket (separated by white space). The final optional element is the conditional that dictates if the line of code should run.

Control Structures

Perl also provides a rich chunk of control structures - if, elsif, else, while, until, for, foreach, do, last, continue, next. They are not very different from the their counterparts in other languages. We will look at these in detail later. But it is important to note here that the scope of these conditionals is defined by a pair of curly braces {...} or by the line of code containing them.
if (1) {
   print "Hello World\n";
}
Is the same as
print "Hello World\n" if (1);

STDIN / STDOUT

The console interaction is generally through the STDIN and STDOUT. Any input taken from the console is available on the STDIN and anything that we print in the code is set to the STDOUT by default. Check out the script below - echo.pl that echoes anything that we typed
#!/bin/perl

print "Enter a string\n";
while (1) {
 $input = ;
 print $input;
}
This script runs in an infinite loop. Anything that you type into the console is echoed back. The first line in the loop reads a line from the STDIN. The second line prints whatever it read.