1. Perl
  2. Basic grammar

The Fastest Master of Perl Basic Syntax

This article is a summary of Perl's basic syntax to learn Perl quickly.

Perl Basic Syntax

Syntax Check

Be sure to write the following two lines first.

use strict;
use warnings;

use strict makes syntax check strict.

use warnings displays warnings to prevent mistakes.

print function

The print function prints a string to the standard output.

print "Hello world";


Perl's comment.

# comment

Variable Declarations

The my keyword declares a variable.

# Scalar variables
my $num;

# Array variables
my @students

# Hash variables
my %month_num;

Execution of Perl Programs

The perl command executes Perl programs.

perl script.pl

If you want to print the output to a file, you can use redirection.

perl script.pl > file.txt

These are executed on CUI envrinements, for example:

Compile check

You can do only compile check without runing the script.

perl -c script.pl

Perl Debugger

Perl has the debugger. To start the debugger, use -d option with the perl command.

perl -d script.pl



You can assign a number to a scalar variable. The number is a integral number or a floating point number.

my $num = 1;
my $num = 1.234;

If the digits is large, underscores can be used as delimiters.

my $num = 100_000_000;

Numbers written in source codes are called numeric literals.

Arithmetic Operations

These are basic arithmetic operations.

# Addition
$num = 1 + 1;

# Subtruction
$num = 1 - 1;

# Multiplication
$num = 1 * 2;

# Division
$num = 1 / 2;

To culcurate the quotient, perform division and then extract the integer part using the int function.

# Quotient
$quo = int(3 / 2);

The % operator calculates the remainder.

# Remainder
$mod = 3 % 2;

Increment and decrement

Increment and Decrement.

# Increment

# Decrement


Single Quoted Strings

This is a single quoted string. You can assign it to a scalar varialbe.

my $str1 = 'abc';

Double Quoted Strings

This is a double quoted string. You can assign it to a scalar varialbe. In double quoted strings, you can use escape sequences such as \t(tab), \n(line break) or etc.

my $str2 = "def";
my $str3 = "a\tbc\n";

You can also use variable expansions in double quoted strings.

# Variable expansion - The result is "abc def"
my $str4 = "$str1 def";

String Operators and Functions

Often used string operators and functions.


# Concat two strings
my $join1 = 'aaa' . ' Bbb';

# Concat strings with a delimiter
my $join2 = join(',','aaa', 'bbb', 'ccc');

# Split
my @record = split(/,/, 'aaa,bbb,ccc');

# Length
my $length = length 'abcdef';

# Cut - The result is "ab"
my $substr = substr('abcd', 0, 2);

# Search - Returns the found position, otherwise returns -1
my $result = index('abcd', 'cd');


Explains Perl arrays. Arrays are data structures to have multiple values.

Array Declarations

This is an array declaration and assignment. A list can be assigned to an array.

# Array declarations
my @array;

# Assignment to the array
@array = (1, 2, 3);

Getting and Setting an Element of the Array

Set and get an element of the array.

# Get an element of the array

# Set an element of the array
$array[0] = 1;
$array[1] = 2;

The Length of the Array

To get the length of the array, By evaluating the array in a scalar context, you can get the length of the array.

# Get the legnth of the array
my $array_length = @array;

Array Functions

Often used array functions.

# Cut off the first element
my $first = shift @array;

# Add an element at the beginning of the array
unshift @array, 5;

# Cut off the last element
my $last = pop @array;

# Add an element at the end of the array
push @array, 9;


Explains Perl hashes. Hashes are data structures that have key-value pairs.

Hash Declarations

This is a hash declaration. A list can be assigned to a hash.

# Hash declaration
my %hash;

# Assignment values to the hash
%hash = (a => 1, b => 2);

Getting and Setting a Value of the Hash

Get and set a value of the hash.

# Get a value of the hash

# Set a value of the hash
$hash{a} = 5;
$hash{b} = 7;

If the key of the hash is not consists of "a-zA-Z0-9_", it must be enclosed in single or double quotes.

$hash{'some-key'} = 5;

Hash Functions

Often used hash functions.

# Get all keys
my @keys = keys %hash;

# Get all values
my @values = values %hash;

# Check if the key exists
exists $hash{a};

# Delete a key of the hash
delete $hash{a};

Conditional Branches

Explains conditional branches.

if Statements

For conditional branches, You can use if statements.

if ($condition) {
  # If the condition is ture, the statements in this block are executed.

if-else statement

This is a if-else statement.

if ($condition) {
  # If the condition is ture, the statements in this block are executed.
else {
  # If the condition is false, the statements in this block are executed.

if-elsif Statements

This is a if-elsif statement.

if ($condition1) {
  # If the condition 1 is ture, the statements in this block are executed.
elsif ($condition1) {
  # If the condition 2 is ture, the statements in this block are executed.

Comparison operator

The list of Perl comparison operators. Perl has numeric comparison operators and string comparison operators.

Numeric Comparison Operators

Numeric comparison compares the values as numbers.

$x == $y $x is equal to $y
$x != $y $x is not equal to $y
$x < $y $x is less than $y
$x > $y $x is greater than $y
$x <= $y $x is less than or equal to $y
$x >= $y $x is greater than or equal to $y

String Comparison Operators

String comparison operators compares the values as strings. The values are compared with the dictionary order.

$x eq $y $x is equal to $y
$x ne $y $x is not equal to $y
$x lt $y $x is less than $y
$x gt $y $x is greater than $y
$x le $y $x is less than or equal to $y
$x ge $y $x is greater than or equal to $y

Loop Syntax

Explains loop syntax such as while/for.

The while statement

This is a while statement.

my $i = 0;
while ($i < 5) {
    # Do something

The for statement

This is a for statement.

for (my $i = 0; $i < 5; $i++) {
  # Do something

The foreach statement

This is a foreach statement to iterate each element of the array.

foreach my $num (@nums) {
  # Do something

In Perl, the foreach statement is alias for the for statement.

# Same as the above foreach statement
for my $num (@nums) {
  # Do something


Explaines subroutines.

Subroutine Definition

This is a subroutine defintiion. A subroutine recieves the arguments, execute the statements, and return the return values.

sub sum {
  # Revices arguments
  my ($num1, $num2) = @_;
  # Execute the statements
  my $total = $num1 + $num2;
  # Return the return values
  return $total;

Calling Subroutines

Call a subroutine.

# Call a subroutine
my $sum = sum(1, 2);

File Input/Output

Explains file Input/Output.

# Open file
open my $fh, '<', $file
  or die "Cannot open'$file':$!";

while (my $line = <$fh>) {

close $fh;

The open function opens a file. The "<" means the read mode.

The <$fh> is a line input operator.

$! is a predefined variable to be set to the error that the operating system returns.

Often Used Features

Explains Perl often used features.

Perl True and False Values

Explains Perl true and false values.

False Values

These are false values in Perl.

  • undef
  • 0
  • ""
  • "0"
  • ()
True Values

True values are all values except for the above false values.

The defined Function

The defined function checks if the value is defined.

defined $num;

Command Line Arguments

@ARGV is command line arguments.

my ($args0, $args1, $args2) = @ARGV;

Scalar Context and List Context

Perl has context that the value is evaluated.

These are examples that the return values are different corresponding to scalar context and list context.

# Scalar context
my $time_str = localtime();

# List contex
my @datetime = localtime();

The unless Statement

Perl has the unless statement.

unless ($condition) {

The above unless statement is same as the following if statement.

if (!$condition) {

Postfix if, Postfix unless

Perl has the postfix if statement and the postfix unless statement.

# Postfix if
print $num if $num > 3;

# Postfix unless
die "error" unless $num;

Postfix for

Per has the postfix for statement.

# Postfix for
print $_ for @nums;

Each element of the array is assigned to $_.

$_ is called default variables

Array Slices and Hash Slices

Perl has array slices and hash slices syntax to get the specified elements.

# Array slice
my @select = @array[1, 4, 5];

# Hash slice
my @select = @hash{'a', 'b', 'd'};

The map Function

Perl has the map function to process each element of the array. Each element is assigned to $_.

my @mapped = map {$_ * 2} @array;

The above result of the map funtion is same as the result of the following for statement.

my @mapped;
for my $elem (@array) {
  my $new_elem = $elem * 2;
  push @mapped, $new_elem;

The grep function

Perl has the grep function to get the elements that the condition match. Each element is assigned to $_.

my @select = grep {$_ =~ /cat/} @array;

The above result of the grep function is same as the result of the following for statement.

my @select;
for my $elem (@array) {
  if ($elem =~ /cat/) {
    push @select, $elem;

List Assignment

This is the syntax of list assignment.

# List assignment
my ($num1, $num2) = ($num3, $num4);

The Range Operator

The range operator creates a list that has a range of integers.

# Range operator
my @numes = (0 .. 5);

This is same as the following code.

my @numes = (0, 1, 2, 3, 4, 5);

The string list operator

Perl has the string list operator to create a string list easily.

# String list operator
my @strs = qw(aaa bbb ccc);

This is same as the following code.

my @strs = ('aaa', 'bbb',  'ccc');

Return Statments that has No Operand

The return statments that has no operand returns undef in scalar context, or returns an empty list in list context.

sub foo {

# undef
my $ret = foo();

# ()
my @ret = foo();

Exception Handling

The die function throws an exception.

# Throw an exception
die "Error message";

The eval block catch exceptions. If an exception occurs, the exception message is assinged to the predefined variable "$@".

# Catch exceptions
eval {
  # Do something

# The exception message
if ($@) {

Read Whole Content from a File

To read whole content from a file, you can use the following syntax.

# Read whole content from a file
my $content = do { local $/; <$fh> };

The Ternary Operator

Perl has Ternary operator.

# Ternary operator
my $num = $flag ? 1 : 2;


Perl has special assign operator "||=".

$num ||= 2;

This is same as the following code.

$num = $num || 2;


Perl has the defined-or operator and the special assign operator.

$num //= 2;

This is same as the following code.

$num = $num // 2;

Module Loading

The use function loads a module.

use SomeModule;

Write a configuration file in Perl

The do function read the configuration file written by Perl.

use FindBind;
my $conf_file = "$FindBin::Bin/app.conf";
my $conf = do $conf_file
  or die "Can't load config file \"$conf_file\":$! $@";

Examples of config file:

  name =>'Foo',
  number => 9

Multiple Line Comments

Although Perl has not the syntax of multiple line comments, You can use POD syntax to write multiple line comments.






Related Informatrion