DEV Community

Yuki Kimoto
Yuki Kimoto

Posted on

The Fastest Master of Perl Basic Syntax 2022

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

The original article is The Fastest Master of Perl Basic Synta | Perl ABC

Perl Basic Syntax

Syntax Check

Be sure to write the following two lines first.

use strict;
use warnings;
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

Comments

Perl's comment.

# comment
Enter fullscreen mode Exit fullscreen mode

Variable Declarations

The my keyword declares a variable.

# Scalar variables
my $num;

# Array variables
my @students

# Hash variables
my %month_num;
Enter fullscreen mode Exit fullscreen mode

Execution of Perl Programs

The perl command executes Perl programs.

perl script.pl
Enter fullscreen mode Exit fullscreen mode

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

perl script.pl > file.txt
Enter fullscreen mode Exit fullscreen mode

These are executed on CUI envrinements, for example:

Compile check

You can do only compile check without runing the script.

perl -c script.pl
Enter fullscreen mode Exit fullscreen mode

Perl Debugger

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

perl -d script.pl
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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

my $num = 100_000_000;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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

# Quotient
$quo = int(3 / 2);
Enter fullscreen mode Exit fullscreen mode

The % operator calculates the remainder.

# Remainder
$mod = 3 % 2;
Enter fullscreen mode Exit fullscreen mode

Increment and decrement

Increment and Decrement.

# Increment
$i++

# Decrement
$i--
Enter fullscreen mode Exit fullscreen mode

Strings

Single Quoted Strings

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

my $str1 = 'abc';
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

You can also use variable expansions in double quoted strings.

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

String Operators and Functions

Often used string operators and functions.

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');
Enter fullscreen mode Exit fullscreen mode

Arrays

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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Hashes

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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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};
Enter fullscreen mode Exit fullscreen mode

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.
}
Enter fullscreen mode Exit fullscreen mode

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.
}
Enter fullscreen mode Exit fullscreen mode

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.
}
Enter fullscreen mode Exit fullscreen mode

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.

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.

The while statement

This is a while statement.

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

    # Do something

    $i++;
}
Enter fullscreen mode Exit fullscreen mode

The for statement

This is a for statement.

for (my $i = 0; $i < 5; $i++) {
  # Do something
}
Enter fullscreen mode Exit fullscreen mode

The foreach statement

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

foreach my $num (@nums) {
  # Do something
}
Enter fullscreen mode Exit fullscreen mode

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

# Same as the above foreach statement
for my $num (@nums) {
  # Do something
}
Enter fullscreen mode Exit fullscreen mode

Subroutines

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;
}
Enter fullscreen mode Exit fullscreen mode

Calling Subroutines

Call a subroutine.

# Call a subroutine
my $sum = sum(1, 2);
Enter fullscreen mode Exit fullscreen mode

File Input/Output

Explains file Input/Output.

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

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

close $fh;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Command Line Arguments

@ARGV is command line arguments.

my ($args0, $args1, $args2) = @ARGV;
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

The unless Statement

Perl has the unless statement.

unless ($condition) {
  ...
}
Enter fullscreen mode Exit fullscreen mode

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

if (!$condition) {
  ...
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Postfix for

Per has the postfix for statement.

# Postfix for
print $_ for @nums;
Enter fullscreen mode Exit fullscreen mode

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'};
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

List Assignment

This is the syntax of list assignment.

# List assignment
my ($num1, $num2) = ($num3, $num4);
Enter fullscreen mode Exit fullscreen mode

The Range Operator

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

# Range operator
my @numes = (0 .. 5);
Enter fullscreen mode Exit fullscreen mode

This is same as the following code.

my @numes = (0, 1, 2, 3, 4, 5);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

This is same as the following code.

my @strs = ('aaa', 'bbb',  'ccc');
Enter fullscreen mode Exit fullscreen mode

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 {

  return;
}

# undef
my $ret = foo();

# ()
my @ret = foo();
Enter fullscreen mode Exit fullscreen mode

Exception Handling

The die function throws an exception.

# Throw an exception
die "Error message";
Enter fullscreen mode Exit fullscreen mode

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 ($@) {
  ...
}
Enter fullscreen mode Exit fullscreen mode

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> };
Enter fullscreen mode Exit fullscreen mode

The Ternary Operator

Perl has Ternary operator.

# Ternary operator
my $num = $flag ? 1 : 2;
Enter fullscreen mode Exit fullscreen mode

||=

Perl has special assign operator "||=".

$num ||= 2;
Enter fullscreen mode Exit fullscreen mode

This is same as the following code.

$num = $num || 2;
Enter fullscreen mode Exit fullscreen mode

//=

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

$num //= 2;
Enter fullscreen mode Exit fullscreen mode

This is same as the following code.

$num = $num // 2;
Enter fullscreen mode Exit fullscreen mode

Module Loading

The use function loads a module.

use SomeModule;
Enter fullscreen mode Exit fullscreen mode

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\":$! $@";
Enter fullscreen mode Exit fullscreen mode


Examples of config file:

{
  name =>'Foo',
  number => 9
}
Enter fullscreen mode Exit fullscreen mode

Multiple Line Comments

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

=pod

Comment1

Comment2

Comment3

=cut
Enter fullscreen mode Exit fullscreen mode

Discussion (0)