The Fastest Master of Perl Basic Syntax 2022
Tags: perl
Published: 2022-03-17 08:18:38

This article is a summary of Perl's basic [syntax](https://en.perlzemi.com/blog/20161022147731.html) 2022 to learn Perl quickly.

The original article is [The Fastest Master of Perl Basic Synta | Perl ABC](https://en.perlzemi.com/blog/20091226126425.html)

## Perl Basic Syntax

### Syntax Check

Be sure to write the following two lines first.

```
use strict;
use warnings;
```

[use strict](https://en.perlzemi.com/blog/20130912137895.html) makes syntax check strict.

[use warnings](https://en.perlzemi.com/blog/20130916137930.html) displays warnings to prevent mistakes.

### print function

The [print function](https://en.perlzemi.com/blog/20170404149131.html) prints a string to the standard output.

```
print "Hello world";
```

### Comments

Perl's [comment](https://en.perlzemi.com/blog/20130712137361.html).

```
# comment
```

### Variable Declarations

The [my](https://en.perlzemi.com/blog/20080307120491.html) keyword declares a [variable](https://en.perlzemi.com/blog/20161107147852.html).

```
# 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:

* [Command Prompt on Windows](https://en.perlzemi.com/blog/20080603121251.html)
* Shell on Mac/[Linux](https://en.linux.perlzemi.com/)/UNIX

### Compile check

You can do only compile check without runing the script.

```
perl -c script.pl
```

### Perl Debugger

Perl has the [debugger](https://en.perlzemi.com/blog/20100302126967.html). To start the debugger, use **-d** option with the **perl** command.

```
perl -d script.pl
```

## Numbers

### Numbers

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](https://en.perlzemi.com/blog/20080826121977.html).

### Arithmetic Operations

These are basic [arithmetic operations](https://en.perlzemi.com/blog/20080910122105.html).

```
# 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](https://en.perlzemi.com/blog/20080923122214.html).

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

The **%** operator calculates the remainder.

```
# Remainder
$mod = 3 % 2;
```

### Increment and decrement

[Increment](https://en.perlzemi.com/blog/20180224151948.html) and [Decrement](https://en.perlzemi.com/blog/20180226151973.html).

```
# Increment
$i++

# Decrement
$i--
```

## Strings

### Single Quoted Strings

This is a [single quoted string](https://en.perlzemi.com/blog/20201027075254.html). You can assign it to a scalar varialbe.

```
my $str1 = 'abc';
```

### Double Quoted Strings

This is a [double quoted string](https://en.perlzemi.com/blog/20201026075254.html).  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](https://en.perlzemi.com/blog/20161005147566.html) and [functions](https://en.perlzemi.com/blog/20161004147558.html).

* [String Concatnation Operator](https://en.perlzemi.com/blog/20080221120361.html)
* [join Function](https://en.perlzemi.com/blog/20081007122338.html)
* [split Function](https://en.perlzemi.com/blog/20080301120434.html)
* [length Function](https://en.perlzemi.com/blog/20080926122245.html)
* [substr Function](https://en.perlzemi.com/blog/20080224120386.html)
* [index Function](https://en.perlzemi.com/blog/20080225120395.html)

**Examples:**

```
# 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');
```

## Arrays

Explains Perl [arrays](https://en.perlzemi.com/blog/20161012147627.html). Arrays are data structures to have multiple values.

### Array Declarations

This is an array declaration and assignment. A [list](https://en.perlzemi.com/blog/20100308126967.html) 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
$array[0];
$array[1];

# 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](https://en.perlzemi.com/blog/20161004147558.html).

```
# 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;
```

## Hashes

Explains Perl [hashes](https://en.perlzemi.com/blog/20161013147635.html). Hashes are data structures that have key-value pairs.

### Hash Declarations

This is a hash declaration. A [list](https://en.perlzemi.com/blog/20100308126967.html) 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
$hash{a};
$hash{b};

# 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](https://en.perlzemi.com/blog/20161004147558.html).

```
# 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](https://en.perlzemi.com/blog/20161023147731.html).

```
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](https://en.perlzemi.com/blog/20080318120585.html). Perl has numeric comparison operators and string comparison operators.

**Numeric Comparison Operators** 

Numeric comparison compares the values as numbers.

|Operators|Meanings|
|---|---|
|      $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.

|Operators|Meanings|
|---|---|
|      $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](https://en.perlzemi.com/blog/20170521149524.html).

### The while statement

This is a [while](https://en.perlzemi.com/blog/20100123126425.html) statement.

```
my $i = 0;
while ($i < 5) {

    # Do something

    $i++;
}
```

### The for statement

This is a [for](https://en.perlzemi.com/blog/20080327120662.html) statement.

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

### The foreach statement

This is a [foreach](https://en.perlzemi.com/blog/20080328120673.html) 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
}
```

## Subroutines

Explaines [subroutines](https://en.perlzemi.com/blog/20101130129876.html). 

### 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](https://en.perlzemi.com/blog/20110212130370.html).

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

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

close $fh;
```

The [open function](https://en.perlzemi.com/blog/20080718121643.html) opens a file. The "<" means the read mode.

The **<$fh>** is a [line input operator](https://en.perlzemi.com/blog/20080722121673.html).

**$!** is a [predefined variable](https://en.perlzemi.com/blog/20161102147817.html) 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](https://en.perlzemi.com/blog/20080323120628.html).

#### 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](https://en.perlzemi.com/blog/20100219126425.html) checks if the value is defined.

```
defined $num;
```

### Command Line Arguments

@ARGV is [command line arguments](https://en.perlzemi.com/blog/20080108132865.html).

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

### Scalar Context and List Context

Perl has [context](https://en.perlzemi.com/blog/20080608121292.html) 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](https://en.perlzemi.com/blog/20100125126425.html).

```
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](https://en.perlzemi.com/blog/20180118151628.html)

### Array Slices and Hash Slices

Perl has [array slices](https://en.perlzemi.com/blog/20080216120316.html) and [hash slices](https://en.perlzemi.com/blog/20080215120307.html) 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](https://en.perlzemi.com/blog/20100118126425.html) 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](https://en.perlzemi.com/blog/20100119126425.html) 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](https://en.perlzemi.com/blog/20100308126967.html) assignment.

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

### The Range Operator

The [range operator](https://en.perlzemi.com/blog/20170520149523.html) 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](https://en.perlzemi.com/blog/20080222120369.html) 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](https://en.perlzemi.com/blog/20100220126425.html) in scalar context, or returns an empty list in list context.

```
sub foo {

  return;
}

# undef
my $ret = foo();

# ()
my @ret = foo();
```

### Exception Handling

The [die function](https://en.perlzemi.com/blog/20100212126425.html) throws an exception.

```
# Throw an exception
die "Error message";
```

The [eval block](https://en.perlzemi.com/blog/20100312126967.html) 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](https://en.perlzemi.com/blog/20180521152690.html), you can use the following syntax.

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

### The Ternary Operator

Perl has [Ternary operator](https://en.perlzemi.com/blog/20080325120646.html).

```
# 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](https://en.perlzemi.com/blog/20120702134129.html) and the special assign operator.

```
$num //= 2;
```

This is same as the following code.

```
$num = $num // 2;
```

### Module Loading

The [use](https://en.perlzemi.com/blog/20090205123287.html) function loads a [module](https://en.perlzemi.com/blog/20091116124667.html).

```
use SomeModule;
```

### Write a configuration file in Perl

The [do function](https://en.perlzemi.com/blog/20090208123289.html) 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](https://en.perlzemi.com/blog/20170408149166.html) syntax to write multiple line comments.

```
=pod

Comment1

Comment2

Comment3

=cut
```