# Perl

Released in early 1988, Perl is a "postmodern" programming language.
It's often considered a scripting language, but it's also capable of object-oriented programming, but its developers pride themselves on its flexibility.
Perl, according to its creator Larry Wall, doesn't enforce any particular style of programming on its users, and there's more than one way to most things.

Although its popularity has been tempered by languages like Python, Lua, and Go, Perl was one of the primary utilitarian languages on Unix and Linux for 30 years.
It remains an important and powerful component to many open source systems.
With over 30 years of development, Perl is a mature langauge with [tens of thousands of libraries](http://cpan.org), GUI frameworks, a spin-off language called Raku, and an active and passionate community.

== Installing Perl

On Linux and macOS, you already have Perl installed.

On Windows, download and install Perl from [perl.org/get.html.](https://www.perl.org/get.html)

## 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`.
`2` returns the value of `2`, and `a` returns the letter `a`.

Expressions can be more complex.
`$a + $b` is a an expression containing 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:

```perl
$c = $a + $b;
```

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

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

## Perl blocks

A block of Perl statements can be grouped together with braces (`{` ` }`).
This is a useful organizational tool, but it also provides *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.
We humans use variables everyday without thinking about it.
For instance, the word "it" can refer to any noun, so we use it (the word) as a convenient placeholder.
"Find my phone and bring it to me" really means "Find my pen 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
$ 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 makes a decision of how the program proceeds based on that condition.
The syntax is similar to C or Java:

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

```perl
$var = 1;

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

## Functions and subroutines

It's important to re-use code as often as possible.
This 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 your program easier to understand by other developers.

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 key word `sub`, followed by a subroutine name of your choosing, and then the code block:

```perl
#!/usr/bin/perl

sub sum{
 my $total = 0;

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

 return $total;
}

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

Of course, Perl has lots of subroutines you never have to create yourself.
Some are built into Perl, and others are provided by community libraries.

== 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 out, especially if you're already familiar with Python or https://opensource.com/article/20/4/bash-programming-guide[shell scripting].

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

```perl
#!/usr/bin/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 https://opensource.com/article/19/7/what-posix-richard-stallman-explains[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 to issue warnings in the terminal about problems it finds.
The `use strict` settings tells Perl not to run the script when there are errors 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](https://opensource.com/article/21/8/linux-terminal) provided to the script when it is launched from a terminal.
In this case, the expected argument is the desired sides of a virtual dice.
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` key word, 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 dice 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:

```perl
$ chmod +x dice.pl
```

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

```perl
$ ./dice.pl 20
1
$ ./dice.lisp 20
7
$ ./dice.lisp 20
20
```

Not bad!

== Learning Perl

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, and with a bright future ahead.
Next time you're looking for something more a flexible language with easy delivery options, try Perl.