Learn Perl in 2022

Download the programming cheat sheet and start learning the powers of Perl.
50 readers like this.
Woman sitting in front of her computer

Ray Smith

Released in early 1988, Perl is a postmodern programming language often considered a scripting language, but it is also capable of object-oriented programming. It is a mature language with tens of thousands of libraries, GUI frameworks, a spin-off language called Raku, and an active and passionate community. Its developers pride themselves on its flexibility: According to its creator Larry Wall, Perl doesn't enforce any particular programming style on its users, and there's more than one way to accomplish most things.

Perl is every bit as robust as it was when it was in widespread use, making it a great language for newer programmers to try.

[ Download the Perl cheat sheet ]

Perl basics

On Linux and macOS, you already have Perl installed. On Windows, download and install it from the Perl website.

Perl expressions

The basic unit of Perl source code is an expression, which is anything that returns a value.

For instance, 1 is an expression. It returns the value of 1. The expression 2 returns the value of 2, and a returns the letter a.

Expressions can be more complex. The expression $a + $b contains variables (placeholders for data) and the plus symbol (+), which is a math operator.

Perl statements

A Perl statement is made up of expressions. Each statement ends in a semi-colon (;).

For example:

$c = $a + $b;

To try running your own Perl statement, open a terminal and type:

$ perl -e 'print ("Hello Perl\n");'

Perl blocks

A block of Perl statements can be grouped together with braces ({ }). Blocks are a useful organizational tool, but they also provide scope for data that you may only need to use for a small section of your program. Python defines scope with whitespace, LISP uses parentheses, while C and Java use braces.

Variables

Variables are placeholders for data. Humans use variables every day without thinking about it. For instance, the word "it" can refer to any noun, so we use it as a convenient placeholder. "Find my phone and bring it to me" really means "Find my phone and bring my phone to me."

For computers, variables aren't a convenience but a necessity. Variables are how computers identify and track data.

In Perl, you create variables by declaring a variable name and then its contents.

Variable names in Perl are always preceded by a dollar sign ($).

These simple statements create a variable $var containing the strings "Hello" and "Perl" and then prints the contents of the variable to your terminal:

$ perl -e '$var = "hello perl"; print ("$var\n");'

Flow control

Most programs require a decision to be made, and those choices are defined and controlled by conditional statements and loops. The if statement is one of the most intuitive: Perl can test for a specific condition, and Perl decides how the program proceeds based on that condition. The syntax is similar to C or Java:

my $var = 1;

if($var == 1){
  print("Hello Perl\n");
}
elsif($var == 0){
  print("1 not found");
}
else{
  print("Good-bye");
}

Perl also features a short form of the if statement:

$var = 1;

print("Hello Perl\n") if($var == 1);

Functions and subroutines

Reusing code as often as possible is a helpful programming habit. This practice reduces errors (or consolidates errors into one code block, so you only have to fix it once), makes your program easier to maintain, simplifies your program's logic, and makes it easier for other developers to understand.

In Perl, you can create a subroutine that takes inputs (stored in a special array variable called @_) and may return an output. You create a subroutine using the keyword sub, followed by a subroutine name of your choosing, and then the code block:

#!/usr/bin/env perl

use strict;
use warnings;

sub sum {
  my $total = 0;

  for my $i(@_){
    $total += $i;
  }

  return($total);
}

print &sum(1,2), "\n";

Of course, Perl has many subroutines you never have to create yourself. Some are built into Perl, and community libraries provide others.

Scripting with Perl

Perl can be compiled, or it can be used as an interpreted scripting language. The latter is the easiest option when just starting, especially if you're already familiar with Python or shell scripting.

Here's a simple dice-roller script written in Perl. Read it through and see if you can follow it.

#!/usr/bin/env perl

use warnings;
use strict;
use utf8;
binmode STDOUT, ":encoding(UTF-8)";
binmode STDERR, ":encoding(UTF-8)";

my $sides = shift or
  die "\nYou must provide a number of sides for the dice.\n";

sub roller {
    my ($s) = @_;

    my $roll = int(rand($s));
    print $roll+1, "\n";
}

roller($sides);

The first line tells your POSIX terminal what executable to use to run the script.

The next five lines are boilerplate includes and settings. The use warnings setting tells Perl to check for errors and issue warnings in the terminal about problems it finds. The use strict setting tells Perl not to run the script when errors are found.

Both of these settings help you find errors in your code before they cause problems, so it's usually best to have them active in your scripts.

The main part of the script begins by parsing the argument provided to the script when it is launched from a terminal. In this case, the expected argument is the desired side of a virtual die. Perl treats this as a stack and uses the shift function to assign it to the variable $sides. The die function gets triggered when no arguments are provided.

The roller subroutine or function, created with the sub keyword, uses the rand function of Perl to generate a pseudo-random number up to, and not including, the number provided as an argument. That means that a 6-sided die in this program can never roll a 6, but it can roll a 0. That's fine for computers and programmers, but to most users, that's confusing, so it can be considered a bug. To fix that bug before it becomes a problem, the next line adds 1 to the random number and prints the total as the die-roll result.

When referencing an argument passed to a subroutine, you reference the special variable @_, which is an array containing everything included in parentheses as part of the function call. However, when extracting a value from an array, the data is cast as a scalar (the $s variable in the example).

A subroutine doesn't run until it's called, so the final line of the script invokes the custom roller function, providing the command's argument as the function's argument.

Save the file as dice.pl and mark it executable:

$ chmod +x dice.pl

Finally, try running it, providing it with a maximum number from which to choose its random number:

$ ./dice.pl 20
1
$ ./dice.pl 20
7
$ ./dice.pl 20
20

Not bad!

Perl cheat sheet

Perl is a fun and powerful language. Although up-and-coming languages like Python, Ruby, and Go have caught many people's attention since Perl was the default scripting language, Perl is no less robust. In fact, it's better than ever, with a bright future ahead.

Next time you're looking for a more flexible language with easy delivery options, try Perl and download the cheat sheet!

Seth Kenlon
Seth Kenlon is a UNIX geek, free culture advocate, independent multimedia artist, and D&D nerd. He has worked in the film and computing industry, often at the same time.
User profile image.
Dave Morriss is a retired IT Manager based in Edinburgh, Scotland. He worked in the UK higher education sector providing IT services to students and staff.

5 Comments

I used Perl extensively in one of my jobs. It is a good language and I found it fairly easy to learn and use. It is also incredibly powerful. I have used Bash for some time now but have been thinking about getting back to Perl for many of my more complex programs. I have found that Bash is a great command line and scripting language but Perl makes it easy to do things that are quite difficult in Bash.

Thanks for a great article!

If you're going to write an article called "Learn Perl in 2022" then you could include some Perl that looks like it was written in the last five years.

You should be using "say()" instead of "print()" in most of your examples.

You don't explain why you use an ampersand when calling "sum()", but not when calling "roller()" - the answer is that an ampersand isn't needed in either case and using it only serves to confuse people (see https://perlhacks.com/2015/04/subroutines-and-ampersands/ for more details).

Oh, and having "use utf8" in your example programs is achieving nothing useful. The "utf8" pragma tells the Perl compiler that your source code includes characters that are encoded as UTF8. All of your code just uses ASCII characters - so that's just adding unnecessary complexity.

Thank you for your helpful comments, Mr. Cross!

I'm glad you're enjoying the say() function. Unlike print(), it adds a newline automatically, so it's a great thing to know. However, I think reinforcing awareness of newlines in programming is helpful for new programmers, because when you have a function that doesn't automatically include them, you understand why you need to insert \n or endl or whatever.

Explicit ampersands are a matter of preference. We stand by this.

We use UTF8 for the same reason we use print(). To many people, UTF8 isn't something they think about, so we use it as a way to reinforce its importance. It will be the default in Perl soon anyway, but for now it's something we use explicitly.

Thanks for reading our article!

In the words of Larry Wall: TMTOWTDI ("There's more than one way to do it".)

In reply to by Dave Cross

I agree that ampersands are a matter of preference. But you use an ampersand in one example - &sum(1,2) - and not in another - roller($sides). It's an inconsistency that you don't explain, so it will just be confusing to newcomers to the language. They will try to work out the reason for the change ("Oh, maybe you need to use '&' if you're passing the return value to print()") and will get it wrong.

If you're going to use an ampersand then please be consistent about it. Alternatively, explain to your readers how you decide whether to use one or not.

The same is true with your use of "use utf8". It's in one of your full programs, but not the other. And because you don't mention it, your readers will be confused as to when they should use it.

When writing tutorials (and, particularly, tutorials aimed at beginners) simplicity and consistency should be your watchwords. Any necessary inconsistencies should be clearly explained and any unnecessary inconsistencies should be removed.

You may be interested in my Perl tutorial for absolute beginners - https://perlhacks.com/perl-taster/

In reply to by sethkenlon

Thanks for the tips. I think you and I differ in our approach to education, but ultimately that's to the benefit of readers.

I'd love to get more Perl content on Opensource.com, so if you're looking for another outlet please do get in touch.

In reply to by Dave Cross

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.