PERLINTRO(1)
π NAME π
perlintro β a brief introduction and overview of Perl. bestie, this is your lil' bootstrap guide, fr fr.
πΈ DESCRIPTION πΈ
Okay so this doc is here to give you a quick overview of the Perl programming language, plus pointers to further documentation. It's meant as a "bootstrap" guide for people who are new to the language, and it gives you just enough to read other people's Perl and understand roughly what it's doing, or to write your own simple scripts. slay.
This introductory document does not aim to be complete. It doesn't even aim to be entirely accurate. In some cases perfection has been sacrificed in the goal of getting the general idea across. You are strongly advised to follow this introduction with more information from the full Perl manual, the table of contents to which can be found in perltoc.
Throughout this document you'll see references to other parts of the Perl documentation. You can read that documentation using the perldoc command or whatever method you're using to read this document.
Throughout Perl's documentation, you'll find numerous examples intended to help explain the discussed features. Please keep in mind that many of them are code fragments rather than complete programs.
These examples often reflect the style and preference of the author of that piece of the documentation, and may be briefer than a corresponding line of code in a real program. Except where otherwise noted, you should assume that use strict and use warnings statements appear earlier in the "program", and that any variables used have already been declared, even if those declarations have been omitted to make the example easier to read.
Do note that the examples have been written by many different authors over a period of several decades. Styles and techniques will therefore differ, although some effort has been made to not vary styles too widely in the same sections. Do not consider one style to be better than others β "There's More Than One Way To Do It" is one of Perl's mottos. After all, in your journey as a programmer, you are likely to encounter different styles.
π¦ What is Perl? π¦
Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more.
The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal). Its major features are that it's easy to use, supports both procedural and object-oriented (OO) programming, has powerful built-in support for text processing, and has one of the world's most impressive collections of third-party modules. iconic.
Different definitions of Perl are given in perl, perlfaq1 and no doubt other places. From this we can determine that Perl is different things to different people, but that lots of people think it's at least worth writing about.
πββοΈ Running Perl programs πββοΈ
To run a Perl program from the Unix command line:
perl progname.pl
Alternatively, put this as the first line of your script:
#!/usr/bin/env perl
... and run the script as /path/to/script.pl. Of course, it'll need to be executable first, so chmod 755 script.pl (under Unix).
(This start line assumes you have the env program. You can also put directly the path to your perl executable, like in #!/usr/bin/perl).
For more information, including instructions for other platforms such as Windows, read perlrun.
π Safety net π
Perl by default is very forgiving. In order to make it more robust it is recommended to start every program with the following lines:
#!/usr/bin/perl
use strict;
use warnings;
The two additional lines request from perl to catch various common problems in your code. They check different things so you need both. A potential problem caught by use strict; will cause your code to stop immediately when it is encountered, while use warnings; will merely give a warning (like the command-line switch -w) and let your code run. To read more about them, check their respective manual pages at strict and warnings.
A use v5.35 (or higher) declaration will enable both strict and warnings:
#!/usr/bin/perl
use v5.35;
In addition to enabling the strict and warnings pragmata, this declaration will also activate a "feature bundle"; a collection of named features that enable many of the more recent additions and changes to the language, as well as occasionally removing older features found to have been mistakes in design and discouraged.
β¨ Basic syntax overview β¨
A Perl script or program consists of one or more statements. These statements are simply written in the script in a straightforward fashion. There is no need to have a main() function or anything of that kind.
Perl statements end in a semi-colon:
print "Hello, world";
Comments start with a hash symbol and run to the end of the line
# This is a comment
Whitespace is irrelevant:
print
"Hello, world"
;
... except inside quoted strings:
# this would print with a linebreak in the middle
print "Hello
world";
Double quotes or single quotes may be used around literal strings:
print "Hello, world";
print 'Hello, world';
However, only double quotes "interpolate" variables and special characters such as newlines ("\n"):
print "Hello, $name\n"; # works fine
print 'Hello, $name\n'; # prints $name\n literally
Numbers don't need quotes around them:
print 42;
You can use parentheses for functions' arguments or omit them according to your personal taste. They are only required occasionally to clarify issues of precedence.
print("Hello, world\n");
print "Hello, world\n";
More detailed information about Perl syntax can be found in perlsyn.
πͺ Perl variable types πͺ
You may have noticed the strange character string <$name> above. That denotes a variable, which is generally pronounced as "name". The dollar sign is called a "sigil", and indicates that "name" is a variable. Unlike many other computer languages where variables are just strings of typically only alphabetic and numeric characters, all Perl variables are preceded by a sigil.
Perl has three main variable types: scalars, arrays, and hashes. The particular sigil used for a variable name indicates the type of that variable. We've already seen the dollar sign used as a sigil, $name. The dollar sign indicates this variable is a scalar.
π« Scalars
A scalar represents a single value:
my $animal = "camel";
my $answer = 42;
Scalar values can be strings, integers or floating point numbers, and Perl will automatically convert between them as required. You have to declare them using the my keyword the first time you use them. (This is one of the requirements of use strict;.)
Scalar values can be used in various ways:
print $animal;
print "The animal is $animal\n";
print "The square of $answer is ", $answer * $answer, "\n";
Perl defines a number of special scalars with short names, often single punctuation marks or digits. These variables are used for all kinds of purposes, and are documented in perlvar. The only one you need to know about for now is $_ which is the "default variable". It's used as the default argument to a number of functions in Perl, and it's set implicitly by certain looping constructs.
print; # prints contents of $_ by default
π Arrays
An array represents a list of values. A @ sigil indicates a variable is an array:
my @animals = ("camel", "llama", "owl");
my @numbers = (23, 42, 69);
my @mixed = ("camel", 42, 1.23);
Each of these arrays is an aggregation of individual values. And each value is actually a scalar.
Arrays are zero-indexed. Here's how you get at the individual scalar elements in an array:
print $animals[0]; # prints "camel"
print $animals[1]; # prints "llama"
In Perl, scalars are always referenced with the $ sigil. Thus we wrote $animals[0] above to get the 0th scalar variable inside the @animals array. The square brackets [...] indicate that it is an array that we are getting the value from. This is a major point of confusion for newcomers to Perl. When you are looking at a single value, you need to use $, even though that value is part of a larger aggregation.
The special variable $#array tells you the index of the last element of an array:
print $mixed[$#mixed]; # last element, prints 1.23
You might be tempted to use $#array + 1 to tell you how many items there are in an array. Don't bother. As it happens, using @array where Perl expects to find a scalar value ("in scalar context") will give you the number of elements in the array:
if (@animals < 5) { ... }
The elements we're getting from the array start with a $ because we're getting just a single value out of the array; you ask for a scalar, you get a scalar.
To get multiple values from an array:
@animals[0,1]; # gives ("camel", "llama");
@animals[0..2]; # gives ("camel", "llama", "owl");
@animals[1..$#animals]; # gives all except the first element
This is called an "array slice". We used the @ sigil here because we want multiple values; $ is reserved for referencing single values.
You can do various useful things to lists:
my @sorted = sort @animals;
my @backwards = reverse @numbers;
There are a couple of special arrays too, such as @ARGV (the command line arguments to your script) and @_ (the arguments passed to a subroutine). These are documented in perlvar.
π Hashes
A hash represents a set of key/value pairs. A % sigil indicates a variable is a hash:
my %fruit_color = ("apple", "red", "banana", "yellow");
You can use whitespace and the => operator to lay them out more nicely:
my %fruit_color = (
apple => "red",
banana => "yellow",
lime => "green",
);
To get at hash elements:
$fruit_color{"apple"}; # gives "red"
Note again the use of the $ sigil to access a single hash element. The curly braces {...} indicate that it is an hash that we are getting the value from.
And we can get multiple values using a slice π
my @non_red = @fruit_color{"banana", "lime"};
print $non_red[0], "\n"; # yellow
print $non_red[1], "\n"; # green
okay so quick reminder bestie: when you're grabbing multiple values you use the @ sigil, and when it's just one lil value you use $. π
You can get at lists of the keys and values with keys() and values().
my @fruits = keys %fruit_color;
my @colors = values %fruit_color;
Hashes have no particular internal order (they're lowkey chaotic π), though you can sort the keys and loop through them.
Just like special scalars and arrays, there are also special hashes. The most well known of these is %ENV which contains environment variables. Read all about it (and other special variables) in perlvar.
Scalars, arrays and hashes are documented more fully in perldata.
Note that $name, @name, and %name are three different variables. It can be confusing to use the same alphanumerics to represent different variables, but in some situations it might be clarifying; one such could be to use $name to represent the particular element currently of interest within the array @name. The naming choice is yours; the Perl interpreter doesn't care. When multiple variables have the same name, using square brackets versus curly braces tells the interpreter which one is meant.
More complex data types can be constructed using references, which allow you to build lists and hashes within lists and hashes.
A reference is a scalar value and can refer to any other Perl data type. So by storing a reference as the value of an array or hash element, you can easily create lists and hashes within lists and hashes. The following example shows a 2 level hash of hash structure using anonymous hash references.
my $variables = {
scalar => {
description => "single item",
sigil => '$',
},
array => {
description => "ordered list of items",
sigil => '@',
},
hash => {
description => "key/value pairs",
sigil => '%',
},
};
print "Scalars begin with a $variables->{'scalar'}->{'sigil'}\n";
Exhaustive information on the topic of references can be found in perlreftut, perllol, perlref and perldsc.
β¨ Variable scoping β¨
Throughout the previous section all the examples have used the syntax:
my $var = "value";
The my is actually not required; you could just use:
$var = "value";
However, the above usage will create global variables throughout your program, which is bad programming practice. my creates lexically scoped variables instead. The variables are scoped to the block (i.e. a bunch of statements surrounded by curly-braces) in which they are defined.
my $x = "foo";
my $some_condition = 1;
if ($some_condition) {
my $y = "bar";
print $x; # prints "foo"
print $y; # prints "bar"
}
print $x; # prints "foo"
print $y; # prints nothing; $y has fallen out of scope
Using my in combination with a use strict; at the top of your Perl scripts means that the interpreter will pick up certain common programming errors. For instance, in the example above, the final print $y would cause a compile-time error and prevent you from running the program. Using strict is highly recommended.
β¨ Conditional and looping constructs β¨
Perl has most of the usual conditional and looping constructs.
The conditions can be any Perl expression. See the list of operators in the next section for information on comparison and boolean logic operators, which are commonly used in conditional statements.
πΈ if πΈ
if ( condition ) {
...
} elsif ( other condition ) {
...
} else {
...
}
There's also a negated version of it:
unless ( condition ) {
...
}
This is provided as a more readable version of if (!condition).
Note that the braces are required in Perl, even if you've only got one line in the block. However, there is a clever way of making your one-line conditional blocks more English like:
# the traditional way
if ($zippy) {
print "Yow!";
}
# the Perlish post-condition way
print "Yow!" if $zippy;
print "We have no bananas" unless $bananas;
π¦ while π¦
while ( condition ) {
...
}
There's also a negated version, for the same reason we have unless:
until ( condition ) {
...
}
You can also use while in a post-condition:
print "LA LA LA\n" while 1; # loops forever
β for β
Exactly like C:
for ($i = 0; $i <= $max; $i++) {
...
}
The C style for loop is rarely needed in Perl since Perl provides the more friendly list scanning foreach loop.
π foreach π
foreach (@array) {
print "This element is $_\n";
}
print $list[$_] foreach 0 .. $max;
# you don't have to use the default $_ either...
foreach my $key (keys %hash) {
print "The value of $key is $hash{$key}\n";
}
The foreach keyword is actually a synonym for the for keyword. See "Foreach Loops" in perlsyn.
For more detail on looping constructs (and some that weren't mentioned in this overview) see perlsyn.
β¨ Builtin operators and functions β¨
Perl comes with a wide selection of builtin functions. Some of the ones we've already seen include print, sort and reverse. A list of them is given at the start of perlfunc and you can easily read about any given function by using perldoc -f functionname.
Perl operators are documented in full in perlop, but here are a few of the most common ones:
π Arithmetic π
+ addition
- subtraction
* multiplication
/ division
π Numeric comparison π
== equality
!= inequality
< less than
> greater than
<= less than or equal
>= greater than or equal
π String comparison π
eq equality
ne inequality
lt less than
gt greater than
le less than or equal
ge greater than or equal
(Why do we have separate numeric and string comparisons? Because we don't have special variable types, and Perl needs to know whether to sort numerically (where 99 is less than 100) or alphabetically (where 100 comes before 99).
π Boolean logic π
&& and
|| or
! not
(and, or and not aren't just in the above table as descriptions of the operators. They're also supported as operators in their own right. They're more readable than the C-style operators, but have different precedence to && and friends. Check perlop for more detail.)
π Miscellaneous π
= assignment
. string concatenation
x string multiplication (repeats strings)
.. range operator (creates a list of numbers or strings)
Many operators can be combined with a = as follows:
$x += 1; # same as $x = $x + 1
$x -= 1; # same as $x = $x - 1
$x .= "\n"; # same as $x = $x . "\n";
β¨ Files and I/O β¨
You can open a file for input or output using the open() function. It's documented in extravagant detail in perlfunc and perlopentut, but in short:
open(my $in, "<", "input.txt") or die "Can't open input.txt: $!";
open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
You can read from an open filehandle using the <> operator. In scalar context it reads a single line from the filehandle, and in list context it reads the whole file in, assigning each line to an element of the list:
my $line = <$in>;
my @lines = <$in>;
Reading in the whole file at one time is called slurping. It can be useful but it may be a memory hog. Most text file processing can be done a line at a time with Perl's looping constructs.
The <> operator is most often seen in a while loop:
while (<$in>) { # assigns each line in turn to $_
print "Just read in this line: $_";
}
We've already seen how to print to standard output using print(). However, print() can also take an optional first argument specifying which filehandle to print to:
print STDERR "This is your final warning.\n";
print $out $record;
print $log $logmessage;
When you're done with your filehandles, you should close() them (though to be honest, Perl will clean up after you if you forget):
close $in or die "$in: $!";
β¨ Regular expressions β¨
Perl's regular expression support is both broad and deep, and is the subject of lengthy documentation in perlrequick, perlretut, and elsewhere. However, in short:
π Simple matching π
if (/foo/) { ... } # true if $_ contains "foo"
if ($x =~ /foo/) { ... } # true if $x contains "foo"
The // matching operator is documented in perlop. It operates on $_ by default, or can be bound to another variable using the =~ binding operator (also documented in perlop).
π Simple substitution π
s/foo/bar/; # replaces foo with bar in $_
$x =~ s/foo/bar/; # replaces foo with bar in $x
$x =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar
# in $x
The s/// substitution operator is documented in perlop.
π More complex regular expressions π
You don't just have to match on fixed strings. In fact, you can match on just about anything you could dream of by using more complex regular expressions. These are documented at great length in perlre, but for the meantime, here's a quick cheat sheet:
. a single character
\s a whitespace character (space, tab, newline, ...)
\S non-whitespace character
\d a digit (0-9)
\D a non-digit
\w a word character (a-z, A-Z, 0-9, _)
\W a non-word character
[aeiou] matches a single character in the given set
[^aeiou] matches a single character outside the given
set
(foo|bar|baz) matches any of the alternatives specified
^ start of string
$ end of string
okay so quick recap bestie: $ does NOT match a dollar sign. Not even a little. And same energy for ., \, [, ], (, ), and ^ β they do not match the characters you'd expect either. These lil divas are called metacharacters. π
Meanwhile the characters a, e, i, o, and u? Total sweethearts. Not metacharacters. They match themselves, literally, no drama. So yeah β metacharacters normally match something that isn't their literal value. And heads up, there are a few more metacharacters than the ones listed above β some quantifier ones are coming right up below, and the full list lives in "Metacharacters" in perlre.
So how do you make a metacharacter behave and match its literal self? You "escape" it (aka "quote" it) by putting a backslash in front of it. So \$ does match a dollar sign, and \\ matches a literal backslash. π«Ά
Also also β note that up there, the string \s for example does not match a backslash followed by the letter s. Nope. In that case, putting a backslash before the non-metacharacter s turns it into something that doesn't match its literal value. That kind of sequence is called an "escape sequence", and perlrebackslash documents every single one that currently exists.
β οΈ A warning gets raised if you escape a character that isn't a metacharacter and isn't part of a currently defined escape sequence. So likeβ¦ don't do that. π
β¨ Quantifiers β¨
You can tell Perl how many of the previous thing you want to match by using quantifiers. And when I say "thing," I mean one of exactly these:
- a literal character
- one of the constructs listed above
- a group of either of them, wrapped in parentheses
*β zero or more of the previous thing+β one or more of the previous thing?β zero or one of the previous thing{3}β matches exactly 3 of the previous thing{3,6}β matches between 3 and 6 of the previous thing{3,}β matches 3 or more of the previous thing
Some brief examples, bestie, so it actually clicks:
/^\d+/ string starts with one or more digits
/^$/ nothing in the string (start and end are
adjacent)
/(\d\s){3}/ three digits, each followed by a whitespace
character (eg "3 4 5 ")
/(a.)+/ matches a string in which every odd-numbered
letter is a (eg "abacadaf")
# This loop reads from STDIN, and prints non-blank lines:
while (<>) {
next if /^$/;
print;
}
π Parentheses for capturing π
So parentheses are doing double duty β not just grouping, they also serve a second purpose: they can capture the results of parts of the regexp match so you can use them later. Those results land in $1, $2, and so on. It's giving β¨main character dataβ¨.
# a cheap and nasty way to break an email address up into parts
if ($email =~ /([^@]+)@(.+)/) {
print "Username is $1\n";
print "Hostname is $2\n";
}
π¦ Other regexp features π¦
Perl regexps also support backreferences, lookaheads, and all kinds of other complex details. Read all about them in perlrequick, perlretut, and perlre. π
πΈ Writing subroutines πΈ
Writing subroutines is easy, no cap:
sub logger {
my $logmessage = shift;
open my $logfile, ">>", "my.log" or die "Could not open my.log: $!";
print $logfile $logmessage;
}
And now we can use the subroutine just as any other built-in function:
logger("We have a logger subroutine!");
Now you're probably likeβ¦ "bestie what is that shift??" π Okay so: the arguments to a subroutine are available to us as a special array called @_ (see perlvar for more on that). And the default argument to the shift function just happens to be @_. So my $logmessage = shift; shifts the first item off the list of arguments and assigns it to $logmessage. Iconic, honestly.
We can manipulate @_ in other ways too:
my ($logmessage, $priority) = @_; # common
my $logmessage = $_[0]; # uncommon, and ugly
Subroutines can also return values:
sub square {
my $num = shift;
my $result = $num * $num;
return $result;
}
Then use it like:
$sq = square(8);
For more information on writing subroutines, see perlsub. π
π OO Perl π
OO Perl is relatively simple and is implemented using references which know what sort of object they are based on Perl's concept of packages. However β and this is important β OO Perl is largely beyond the scope of this document. Read perlootut and perlobj.
As a beginning Perl programmer, your most common use of OO Perl will be in using third-party modules, which are documented below. π
π§ Using Perl modules π§
Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN https://www.cpan.org/. A number of popular modules are included with the Perl distribution itself. β¨
Categories of modules range from text manipulation to network protocols to database integration to graphics. A categorized list of modules is also available from CPAN.
To learn how to install modules you download from CPAN, read perlmodinstall.
To learn how to use a particular module, use perldoc Module::Name. Typically you will want to use Module::Name, which will then give you access to exported functions or an OO interface to the module.
perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use.
perlmod describes Perl modules in general. perlmodlib lists the modules which came with your Perl installation.
If you feel the urge to write Perl modules, perlnewmod will give you good advice. π
π AUTHOR π
Kirrily "Skud" Robert <skud@cpan.org>
and that's a wrap on the whole page, bestie!! π this whole thing came to you via perl v5.42.3 and it's dated 2026-08-03, filed under PERLINTRO(1). go forth and slay your regexps πβ¨π¦πΈπ
π«Ά
π¦ where this page comes from
- fedora 43: perl-doc 5.42.3-524.fc43 Β· (GPL-1.0-or-later OR Artistic-1.0-Perl) AND Unicode-3.0 AND LicenseRef-Fedora-UltraPermissive
- fedora 44: perl-doc 5.42.3-525.fc44 Β· (GPL-1.0-or-later OR Artistic-1.0-Perl) AND Unicode-3.0 AND LicenseRef-Fedora-UltraPermissive
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms