sources/tech/20220210 Learn Perl in 2022.md
8.9 KiB
Learn Perl in 2022
Download the programming cheat sheet and start learning the powers of Perl.
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][5]("Hello Perl\n");
}
elsif($var == 0){
[print][5]("1 not found");
}
else{
[print][5]("Good-bye");
}
Perl also features a short form of the if
statement:
$var = 1;
[print][5]("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][6]($total);
}
[print][5] &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][8] STDOUT, ":encoding(UTF-8)";
[binmode][8] STDERR, ":encoding(UTF-8)";
my $sides = [shift][9] or
[die][10] "\nYou must provide a number of sides for the dice.\n";
sub roller {
my ($s) = @_;
my $roll = [int][11]([rand][12]($s));
[print][5] $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.lisp 20
7
$ ./dice.lisp 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!
via: https://opensource.com/article/22/2/perl-cheat-sheet
作者:Seth Kenlon 选题:lujun9972 译者:译者ID 校对:校对者ID