articles/perl.md: new article

This commit is contained in:
tocariimaa 2025-03-04 00:38:06 -03:00
parent cbb38a78cf
commit 549438be7c

68
articles/perl.md Normal file
View file

@ -0,0 +1,68 @@
# Perl
Perl is a scripting [programming language](programming_language.md) created by Larry Wall in 1987. Originally meant
for text processing (as a replacement for [AWK](awk.md)) it latter became a general purpose language. It is quite
[bloated](bloat.md) 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](regular_expressions.md) capabilities, although its regex engine is susceptible to catastrophic
backtracking.
It is shipped by default on most [Linux](linux.md) distributions, so it could be used as a replacement for [shell scripts](shell_script.md)
in some applications, but writing such a program in a more efficient language such as [C](c.md) 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:
```perl
use warnings;
use strict;
```
### Sigils
- `$`: scalar value; numbers, strings...
- `@`: [array](array.md)
- `%`: [hash table](hash_table.md)
- `&`: 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:
```perl
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:
```perl
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 Bash's `set -e`):
```perl
use autodie;
```
## Examples
### Hello world
```perl
# 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:
```sh
# you can also pass `-i` to do inline replacement, like in sed
perl -p -e 's/foo/bar/g' files...
```
TODO
## Resources
- [Perl official website](https://www.perl.org/)
- [Perl Maven](https://perlmaven.com/): page containing tutorials and more