Skip to content

What is Perl

Introduction

Perl, the Practical Extraction and Reporting Language, is a high-level scripting language that was developed for Unix-like systems, and it is now widely used across multiple platforms. It was created by Larry Wall in 1987, and it continues to evolve to this day. Perl is an open-source language and is used by developers for various purposes such as web development, system administration, database administration, network programming, and more. In this blog post, we will provide an introductory guide to Perl, covering the basics of the language that can be learned in just 30 minutes.

Getting started example

#!/usr/bin/env perl
print "Command is: $0\n";
for my $arg ( @ARGV ) {
    print $arg, "\n";
}
exit 0;
  • my is a function for declaring variables. We often need a temporary variable to store the variable value obtained in each loop in the for loop. We usually sandwich a my declaration in the for statement, which has the advantage of limiting the scope of $arg to this for loop structure.
  • Perl statements end with a semicolon.

Variable Classification

Scalar

Scalars start with a $ followed by a letter or underscore.

my $num1 = 10;         # 10
my $num2 = $num1 * 10; # 100
my ($num3, $num4, $num5) = (1, $num2 + 1, 3);
$num1 = $num2 = $num3 = 0;

## my can assign either one scalar or multiple scalars at a time, and can also assign continuously.

my $str1 = 'ABC';       # ABC
my $str2 = '$str1 xyz'; # $str1 xyz
my $str3 = "$str1 xyz"; # ABC xyz
## If a variable is contained in double quotes, its value is interpolated, i.e., the variable name is replaced by its content. Variables in single quotes are not interpolated.

my $str5 = 'here is \' and \';  # here is ' and \
## In a single-quoted string, all characters except for two special characters (' (single quote) and \ (backslash)) are kept as they are.

my $str6 = $str1 . "_" . "xyz"; # ABC_xyz
## String concatenation using .

Array

Array names must start with @ followed by a letter or underscore.

my @nums = ( 1, 4, 9, 16 );
my @vars1 = ( "AAA", "BBB", "CCC" );
my @vars2 = ( "aaa", "bbb", "ccc" );

$nums[0] = 0;           # now @nums is: (0, 4, 9, 16)
$nums[4] = 17;          # now @nums is: (0, 4, 9, 16, 17)
$vars1[1] = "DDDD";

## $# followed by the array name represents the index of the last element in the array.
print 'last index of @vars1 is: ',  $#vars1, "\n";
# last index of @vars1 is: 2

## scalar function returns the size of the array, i.e., the number of elements it contains.
print '@vars2 has ', scalar @vars2, " element\n";
# @vars2 has 3 element

Hash

Hash names must start with %.

%pcc_of = (
  'ZheJiang'    => 'HangZhou',
  'JiangXi'     => 'NanChang',
  'XiZang'      => 'LaSa',
);
print $pcc_of{'JiangXi'}, "\n";

## Use the delete function to delete an element.
$one_hash{'akey'} = "something";
print $one_hash{'akey'}, "\n";
delete $one_hash{'akey'};
print $one_hash{'akey'}, "\n";

Variable Combination

%array_of = (
  "keyA" =>  ["a1", "a2", "a3"],
  "keyB" =>  ["b1", "b2"],
);

%hash_of = (
  "keyA" => { "k1" => "valueA1",
              "k2" => "valueA2",
            },
  "keyB" => { "k1" => "valueB1",
              "k2" => "valueB2",
            },
);

Loops

For

for my $var ( @someArray ) {
  if ( condition1 ) {
    last;
  }
  ## Other sentences ;
}
  • If there are nested loops, last; generally only exits the innermost loop.
  • If you need to exit an outer loop, you can use a label.
  • To skip the remaining statements in a loop body and go to the next iteration, use the next; command.
#!/usr/bin/env perl

my ($opt, %value_of_opt);
for my $arg ( @ARGV ) {
    if ( $arg =~ /^-/ ) {
        $opt = $arg;
    }
    else {
        $value_of_opt{$opt} = $arg;
    }
}

for my $opt ( keys %value_of_opt ) {
    print "$opt => $value_of_opt{$opt}\n";
}
exit 0;

Conditional Statements

If

if ( condition1 ) {
    # sentences1
} elsif {
    # sentences2
} else {
    # sentences3
}

True & False

  • If it has not been assigned, it is false.
  • 0, ‘0’, and ‘’ are false.
  • Everything else is true.
my $t1 = 0;   # false
my $t2 = '0'; # false
my $t3 = '' ; # false
my $t4 = ' '; # true

Logical Operators

!
&&
||
not
and
or

Reference

Equivalent to pointers in C, but more convenient and safer to use.

  • To create a reference, use the backslash “”.
  • To parse a reference, use the corresponding symbol according to the data type pointed to by the reference.
## Create.
$sref = \$str;
$aref = \@ARGV;
$href = \%ENV;

## Parse.
$$sref # ($str)  or ${$sref}
@$aref # (@ARGV) or @{$aref}
%$href # (%ENV)  or %{$href}

Subroutines

  • Subroutines are like functions in other languages.
  • Defined by the keyword sub.
  • Enclosed in braces.
my $num = 2;
sub times_three {
  $_[0] = $_[0] * 3;
  print "value: $_[0]\n";
}
times_three($num);
print "num is: $num\n";

Modules

  • A module is generally a file.
  • The filename suffix is often .pm for “Perl Module”.
perl -e "use perl_module"
#!/usr/bin/env perl
use lib "../perl_module";
use My_perl_module_v1;

System Integration

System Command

## Execute an OS command.
system "ls", "/tmp";
system("ls /tmp");
$re = system("ls /opt");

## Get the output of a system command.
my $user = `whoami`;

## Get and set environment variables.
print "\$USER: $ENV{'USER'}\n";
print "\$PATH: $ENV{'PATH'}\n";
$ENV{'some_env'} = some_value;

Reading Files

#!/usr/bin/env perl
open my $fh_input, '<', "./open_file.pl" or die "read file failed: $!";
while ( my $line = <$fh_input> ) {
    print $line;
}
close $fh_input or die "close file failed: $!";

exit 0

Writing Files

#!/usr/bin/env perl
open my $fh_output, '>', "write_file.txt";
print $fh_output "This is an example\n";
close $fh_output;

exit 0;

Reading Directories

#!/usr/bin/env perl
opendir my $dh, "." or die "Error: read directory failed.";
my @filedirs = readdir $dh;
closedir $dh or die "Error: close directory failed.";
for my $f ( @filedirs ) {
    print $f, "\n";
}

exit 0

Creating Directories

mkdir dir_name[, mask]

Further reading

  • Perl one-liners cookbook
  • Learning Perl
  • https://learnxinyminutes.com/docs/perl
  • https://qntm.org/perl_en

Perl Project

  • Webmin (https://github.com/webmin/webmin)
Feedback