Open In App

Perl | Basic Syntax of a Perl Program

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++. Like other Programming Languages, Perl also follows a basic syntax for writing programs for applications and software or writing a simple Perl program. This syntax contains some predefined words known as Keywords, Variables for storing values, expressions, statements for executing the logic, loops for iterating over a variable value, blocks for grouping statements, subroutines for reducing the complexity of the code, etc. All these, when put together, will make a Perl program. A Perl program whether it be a small code for addition of Two numbers or a Complex one for executing web scripts, uses these variables, statements and other parameters that comprise of a program’s syntax.

Sure, here is the basic syntax of a Perl program:

Perl




#!/usr/bin/perl
 
# This is a comment
 
print "Hello, World!\n";
 
# This is another comment


Output

Hello, World!

Let’s break this down:

The first line, #!/usr/bin/perl, is called the shebang line and specifies the path to the Perl interpreter that should be used to run the script.

The # character is used to indicate comments in Perl. Comments are ignored by the interpreter and are used to provide information or context about the code.

The print statement is used to output text to the console or a file. In this case, we are using the print statement to output the string “Hello, World!” to the console, followed by a newline character (\n) to move the cursor to the next line.

The program ends when it reaches the end of the file.

Note that in Perl, statements are terminated with a semicolon (;), and statements can span multiple lines using line continuation (\ character at the end of the line). Perl is a case-sensitive language, so print and Print would be two different statements.

This is a very simple example of a Perl program, but it should give you an idea of the basic syntax and structure of the language.

Variables

Variables are user-defined words that are used to hold the values passed to the program which will be used to evaluate the Code. Every Perl program contains values on which the Code performs its operations. These values can’t be manipulated or stored without the use of a Variable. A value can be processed only if it is stored in a variable, by using the variable’s name. A value is the data passed to the program to perform manipulation operation. This data can be either number, strings, characters, lists, etc. Example:

Values: 
5
geeks
15

Variables:
$a = 5;
$b = "geeks";
$c = 15;

Above example contains one string variable and two integer variables.  

Expressions

Expressions in Perl are made up of variables and an operator symbol. These expressions formulate the operation that is to be performed on the data provided in the respective code. An expression in Perl is something that returns a value on evaluating. An expression can also be simply a value with no variables and operator symbol. It can be an integer or just a string with no variable. Example:

Value 10 is an expression, $x + $y is an expression that returns their sum, etc.

Expressions can be more complex like Regular Expressions which are used to perform operations on Strings and Sub-strings.  

Comments

Perl developers often make use of the comment system as, without the use of it, things can get real confusing, real fast. Comments are useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. Comments are usually helpful to someone maintaining or enhancing your code when you are no longer around to answer questions about it. These are often cited as a useful programming convention that does not take part in the output of the program but improves the readability of the whole program. There are two types of comment in Perl: Single line comments: Perl single line comment starts with hashtag symbol with no white spaces (#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment. Perl’s single line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. See the following code snippet demonstrating single line comment: 

Perl




#!/usr/bin/perl
$b = 10;    # Assigning value to $b
$c = 30;    # Assigning value to $c
 
$a = $b + $c;   # Performing the operation
print "$a";     # Printing the result


Multi-line string as a comment: Perl multi-line comment is a piece of text enclosed within “=” and “=cut”. They are useful when the comment text does not fit into one line; therefore needs to span across lines. Multi-line comments or paragraphs serve as documentation for others reading your code. Perl considers anything written after the ‘=’ sign as a comment until it is accompanied by a ‘=cut’ at the end. Please note that there should be no whitespace after the ‘=’ sign. See the following code snippet demonstrating a multi-line comment: 

Perl




#!/usr/bin/perl
 
=Assigning values to
variable $b and $c
=cut
$b = 10;   
$c = 30;
 
=Performing the operation
and printing the result
=cut
$a = $b + $c;  
print "$a";   


Statements

A statement in Perl holds instructions for the compiler to perform operations. These statements perform the operations on the variables and values during the Run-time. every statement in Perl must end with a semicolon(;). Basically, instructions written in the source code for execution are called statements. There are different types of statements in the Perl programming language like Assignment statement, Conditional statement, Looping statements, etc. These all help the user to get the required output. For example, n = 50 is an assignment statement. Multi-Line Statements: Statements in Perl can be extended to one or more lines by simply dividing it into parts. Unlike other languages like Python, Perl looks for a semicolon to end the statement. Every line between two semicolons is considered as a single statement. When the programmer needs to do long calculations and cannot fit his statements into one line, one can easily divide it into multiple lines. Example:

$x = $a + $b + $c + 
     $d + $e + $f;

Block

A block is a group of statements that are used to perform a relative operation. In Perl, multiple statements can be executed simultaneously (under a single condition or loop) by using curly-braces ({}). This forms a block of statements which gets executed simultaneously. This block can be used to make the program more optimized by organizing the statements in groups. Variables that are declared inside a block have their scope limited to that specific block and will be of no use outside the block. They will get executed only till that specific block is getting executed. Example:

{
     $x = 15;
     $x = $x + 25;
     print($x);
}

In the above code, the variable $x will have its scope limited to this particular block only and will be of no use outside the block. Above block holds statements that have their operations related to each other.  

Functions or Subroutines

A function/Subroutine is a block of code written in a program to perform some specific task. We can relate functions in programs to employees in an office in real life for a better understanding of how functions work. Suppose the boss wants his employee to calculate the annual budget. So how will this process complete? The employee will take information about the statistics from the boss, performs calculations and calculate the budget and shows the result to his boss. Functions work in a similar manner. They take information as a parameter, execute a block of statements or perform operations on these parameters and returns the result. Perl provides us with two major types of functions: Built-in Functions: Perl provides us with a huge collection of built-in library functions. These functions are already coded and stored in the form of functions. To use those we just need to call them as per our requirement like sin(), cos(), chr(), return(), shift(), etc. User Defined Functions: Apart from the built-in functions, Perl allows us to create our own customized functions called the user-defined functions or Subroutines. Using this we can create our own packages of code and use it wherever necessary by simply calling it.  

Loops

Like any other language, loop in Perl is used to execute a statement or a block of statements, multiple times until and unless a specific condition is met. This helps the user to save both time and effort of writing the same code multiple times. Perl supports various types of looping techniques:

  1. for loop
  2. foreach loop
  3. while loop
  4. do…. while loop
  5. until loop
  6. Nested loops

 

Whitespaces and Indentation

Whitespaces in Perl are the blanks that are used between the variables and operators or between keywords, etc. Perl has no effect of whitespaces unless they are used within quotes. Whitespaces such as spaces, tabs, newlines, etc. have the same meaning in Perl if used outside the quotes. Example 1:

$a = $b + $c;
Here, spaces are of no use, 
it will cause no effect even if it is written as 
$a = $b       +         $c;

Example 2:

print "Geeks for Geeks"; 
will print 
Geeks for geeks
whereas, 
print "Geeks       for
                Geeks";   
will print 
Geeks       for
                Geeks

Here, in the above examples, it is shown that whitespaces have their effect only if used within the quotes. Similarly, the process of indentation is used to arrange the code in an organized way to make it easier for the readers. Whenever a block of statements is used then the indentation will help reducing the reading complexity of the code. Example:

Using Indentation:
{
    $a = $b + $c;
    print "$a";
}

Without using Indentation:
{
$a = $b + $c;
print "$a";
}

In the above example, both of the blocks will work in the exact same way but, for codes which have a large number of statements, the use of indentation makes it more compatible with the readers. Though it is not necessary to use Whitespaces and Indentation in your Perl code, but it is a good practice to do the same.  

Keywords

Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. They have a special meaning to the compiler. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. In Perl, keywords include built-in functions as well along with the control words. These keywords can sometimes be used as a variable name but that will result in confusion and hence, debugging of such a program will be difficult. Example:

One can use $print as a variable along with the keyword print().


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads