wiki/articles/perl.md

2.8 KiB

Perl

Perl is a scripting programming language created by Larry Wall in 1987. Originally meant for text processing (as a replacement for AWK) it latter became a general purpose language. It is quite bloated and has only a single relevant implementation (written in C). Also it is known for its syntax, which can be considered as "inelegant" and leading to "write-only" programs, also the extensive use of sigils; marks used before identifiers used as a way of communicating the data type of the underlying identifiers; using the wrong sigil can lead to unexpected type conversion.

Perl includes powerful regex capabilities, although its regex engine is susceptible to catastrophic backtracking.

It is shipped by default on most Linux distributions, so it could be used as a replacement for shell scripts in some applications, but writing such a program in a more efficient language such as C is preferred.

Notes

Stricter language and warnings

This two lines meant to be put at the top of a script serve as boilerplate to make Perl more strict and saner:

use warnings;
use strict;

Sigils

  • $: scalar value; numbers, strings...
  • @: array
  • %: hash table
  • &: functions; rare in "modern" Perl code.

Feature toggling

For its credit, Perl has a decent level of backwards compatibility compared to other scripting languages, so some features that may cause problems with older code are disabled by default. Perl allows enabling a set of features manually, for example here we enable the say function:

use feature 'say';      # this can also be an array of features...

More conveniently, instead of enabling each feature manually one can simply pick a certain version and all of its features will be enabled:

use v5.34;              # enables `say`, `defer`, `try`-`catch` and more...

Automatically die on any error

This makes a Perl script commit suicide if any error is raised (akin to shell script set -e):

use autodie;

Miscellaneous weirdness

  • When calling the Perl interpreter directly, any shebang at the top of the script that doesn't actually call the Perl interpreter itself gets executed, just like the kernel would interpret the shebang.
  • ...

Examples

Hello world

# with the classical `print`:
print "Hello, World!\n";
# with `say`:
say "Hello, World!";

As a replacement for sed

It is possible to use Perl as sed to benefit from its more powerful regex:

# you can also pass `-i` to do inline replacement, like in sed
perl -p -e 's/foo/bar/g' files...

TODO

Resources