Contents
Introduction
(What's Perl?) 
Quotes & Strings
(text and what to do with it)
Operators
(multiplication and more)
Flow Control
(the if's for's and while's)
Functions
(like print)
Regular Expressions
(powerful text tools)
Testing
(decisions, decisions)
Data Types
(keeping stuff in variables)

 Subroutines
(make your own functions)

Useful Functions Indexed by Name
close open reverse
index print substr
length rindex  

 


 

 

 

 

What is Perl?

Perl is a high-level programming language with an eclectic heritage written by Larry Wall and a cast of thousands. It derives from the ubiquitous C programming language and to a lesser extent from sed, awk, the Unix shell, and at least a dozen other tools and languages. Perl's process, file, and text manipulation facilities make it particularly well-suited for tasks involving quick prototyping, system utilities, software tools, system management tasks, database access, graphical programming, networking, and world wide web programming. These strengths make it especially popular with system administrators and CGI script authors, but mathematicians, geneticists, journalists, and even managers also use Perl. Maybe you should, too.

--from the Perl 5 man page

An Example Program

 

 


Variables & Data Types

As you probably know, a variable is a named location in memory that is used to hold data that may be modified by the program. Perl has three scema for keeping data during program execution: scalars, arrays of scalars (also known as lists), and hashes. Arrays are grouped scalars indexed by number, while hashes are indexed by strings.

Scalars

The most basic kind of data structure in Perl is the scalar variable. Scalar variables can hold both strings and numbers. They are identified by a $ followed by the name of the variable. Unlike many other languages, variables in Perl do not have to be declared or classified in advance of when they are needed. For example,

$bodytemp = 98.6;

sets the scalar variable $BodyTemp to 98.6, but you can also assign a
string to exactly the same variable:

$bodytemp = 'normal';

Perl will also accept numbers as strings,

$bodytemp = '098.6';

and still performs arithmetic and other operations on them.

Arrays

An array variable is a list of scalars, hence in perl they are often refered to as lists. They have the same format as scalar variables except that they are prefixed by an @ symbol. The following statements:

@valine = ("gtg", "gtt", "gta", "gtc");
@hydrophobics = ("valine", "leucine","isoleucine");
@weights(117.15, 131.17, 131.17);

assign a four element list to the array variable @valine and a three element list to the array variables @hydrophobics and @weights.

The individual scalar values of an array are accessed by using indices starting from 0, with square brackets used to specify the index. For example:

$hydrophobics[1] # Returns "leucine"

Notice that the @ has changed to a $ because a scalar value is being referenced. The above arrays are one-dimensional but Perl also provides multi-dimensional capabilities as well. For example,

$matrix[0][0] = "A"; # The matrix:
$matrix[0][1] = "B"; #
$matrix[1][0] = "C"; # | "A" , "B" |
$matrix[1][1] = "D"; # | "C" , "D" |

Under the hood, this two-dimensional array is actually a list of lists, but it is generally simpler to think of it as a matrix. We access the 2D array with an indiex for both the row and the column, in that order. This concept can be extended to arrays of even higher dimensions.

Hashes

Basically hashes are arrays which are accessed by a string. They are also refered to as associative arrays.

To define a hash we can use the usual parenthesis notation, but the array itself is prefixed by a % sign. Suppose we want to store all the hydrophobic amino acids with their molecular weights in a single data structure. It would look like this:

%molyweights = ("valine",     117.15,
                "leucine",    131.17,
                "isoleucine", 131.17);

Now we can find the weights of the amino acids with the following expressions

$molyweights{"leucine"}; # Returns 117.15
$molyweights{"valine"};  # Returns 131.17

Notice that like list arrays each % sign has changed to a $ to access an individual element because that element is a scalar. Unlike list arrays the index (in this case the person's name) is enclosed in curly braces.

A entry can be dynamically added to the hash %molyweights with a statement like this,

$molyweights{"glycene"} = 75.07;

Indeed the entire hash array could have been built up in this manner.

Associative arrays do not have any order to their elements but it is possible to access all the elements in turn using the keys function. This is generally how hashes are processed.

A hash can be converted back into a list array just by assigning it to a list array variable. A list array can be converted into a hash by assigning it to a hash variable. Ideally, the list array should have an even number of elements:

@data = %molyweights; 
$data[5]; # Returns 131.17

@data is a list array that has an element for every string and scalar in the hash %molyweights.

 

 


Program Flow Control

 

The following statements may be used to control program flow.

if (EXPR) {BLOCK}
if (EXPR) {BLOCK} else {BLOCK}
if (EXPR) {BLOCK} elsif (EXPR) {BLOCK} ... else {BLOCK}
LABEL for (EXPR; EXPR; EXPR) {BLOCK}
LABEL foreach VAR (LIST) {BLOCK}
LABEL while (EXPR) {BLOCK}
LABEL do {BLOCK} while (EXPR)
LABEL until (EXPR) {BLOCK}
LABEL do {BLOCK} until (EXPR)

(EXPR) refers to a test that evaluates to either TRUE or FALSE, see section on Testing below. A {Block} is a group of statements delimited by curly brackets { } which is or is not executed depending on the outcome of (EXPR). LABEL is the optional text label.

if - conditional branching

SYNTAX

if (EXPR) {BLOCK}
if (EXPR) {BLOCK} else {BLOCK}
if (EXPR) {BLOCK} elsif (EXPR) {BLOCK} ... else {BLOCK}



DESCRIPTION

For the basic if construct. If the logical expression EXPR evaluates to TRUE, the {BLOCK} of statements that forms the target of the if is executed; Otherwise, the {BLOCK} that forms the target of the else is executed, if it exists.

Another common programming construct is the if-elseif ladder. Any number of elseif's can be added between the if and an optional else to test for additional conditions. The conditions are evaluated from the top downward. As soon as a TRUE condition is found, the associated {BLOCK} is executed and the rest of the ladder is bypassed.



EXAMPLES

#
# SIMPLE IF
#
if ($day == "sat") {
   print "Today is Saturday\n";
}


#
# IF - ELSE
#
if ($day == "sat") {
   print "Today is Saturday\n";
}
else {
   print "Today is not Saturday\n";
}


#
#IF - ELSIF - ELSE
#
if ($day == "sat") {
   print "Today is Saturday\n";
}
elsif ($day == "sun") {
   print "Today is Sunday\n";
}
else {
   print "Today is a weekday\n";
}

for - C-style looping structure

SYNTAX

for (INITIALIZE; TEST; INCREMENT) {BLOCK}


DESCRIPTION
This C-style for loop allows for a {BLOCK} of code to be executed repeatedly while the TEST condition is TRUE. This type of loop provides for an itteration counter, also called the loop control variable. The INITIALIZE statement is generally an assignment to set the loop counter to its initial value, while the INCREMENT defines how the counter changes each time the loop is itterated.


EXAMPLES

# print the numbers 1 through 100
for ($i = 1; $i <= 100; $i++) {
   print "$i ";
}


# print the odd numbers 1 through 101
for ($i = 1; $i <= 101; $i = $i + 2) {
   print "$i ";
}


# count down from 10
for ($i = 10; $i >= 1; $i = $i - 1) {
   print "$i ";
}

foreach - iterates over a list

SYNTAX

foreach VAR (LIST) {BLOCK}


DESCRIPTION

The foreach loop iterates over an array or other list-like structure, (LIST), and sets the variable VAR to be each element of the list in turn. The statements to be performed each time are enclosed in a block delimited by curly braces. If LIST is empty then the block of statements is never executed.


EXAMPLES

To go through each item of an array or other list-like structure

foreach $line (@text) {
   print "$line\n";
}

To go through each line of a hash

foreach $person (keys %ages) {
   print "I know the age of $person\n";
}

foreach $age (values %ages) {
   print "Somebody is $age\n";
}

while - loop structure

SYNTAX

while (EXPR) {BLOCK}
do {BLOCK} while (EXPR)


DESCRIPTION

The while statement executes the {BLOCK} of code as long as the conditional expression EXPR is TRUE. With the regular while loop EXPR is tested before {BLOCK} is executed; In the do-while construct EXPR is tested after {BLOCK} is executed, useful when you want to execute the code in {BLOCK} once regardless of what EXPR evaluates to.


EXAMPLES

# count down from 10
$i=10;
while ($i >= 1) {
   print "$i ";
   $i--;
}

# Check input from keyboard
do {
    print "Enter positive nonzero number:";
    $num = <STDIN>;
} while ( $num <= 0 )

until - loop structure

SYNTAX

until (EXPR) {BLOCK}
do {BLOCK} until (EXPR)


DESCRIPTION

The until statement executes the {BLOCK} of code as long as the conditional expression EXPR is FALSE. With the regular until loop EXPR is tested before {BLOCK} is executed; In the do-until construct EXPR is tested after {BLOCK} is executed, useful when you want to execute the code in {BLOCK} once regardless of what EXPR evaluates to.


EXAMPLE

# Check input from keyboard
do {
    print "Enter positive nonzero number:";
    $num = <STDIN>;
} until ( $num > 0 )


Quotes & Strings in Perl

There are two basic types of strings you should know about. Strings enclosed in "" are interpolated while strings enclosed in '' are not. The following examples illustrates this.

Statement Output
print "Larry\nis $age years old"; Larry
is 49 years old
print 'Larry\nis $age years old'; Larry\nis $age years old

 

For stings delimited with double quotes words beginning with "$" or "@" are interpreted as variables. Also the "\n" is used to represent a line terminator, called a "newline". If a character has a special meaning in an interpolated context it can converted into its literal sense by appending a slash-\, this is known as escaping.The following special characters may be useful to you when writing interpolated strings.

(special characters)
\t tab
\n newline
\b backspace
\a alarm (bell)
\$ literal $
\@ literal @

\\
literal \

 

 


Operators

Precidence

Use parentheses when in doubt.

Arithmetic Operators

Math in Perl

x**y exponentiation
-x negation
x/y division
x*y multiplication
x+y addition
x-y subtraction

 

Auto-increment and Auto-decrement

++ and -- work as increment and decrement. That is x++ is equivalent to x = x + 1. If placed before a variable, they increment or decrement the variable before returning the value, and if placed after, increment or decrement the variable after returning the value. These are most often used for loop counters.

Assignment Operators

= is the ordinary assignment operator.

The value on the right side is placed into a variable on the left. The assignment operator can also be appended to other operators,

$a += 2 is equivalent to $a = $a + 2; both add 2 to $a.

Other assignment operators work similarly:

**= += *= -= /=

String Operators

. concatenates two strings. For example,

$a = 'winter'.'green'; # $a is wintergreen
$b = $c . $d; # Concatenate $c and $d and place in $b

=~ binds a scalar to a pattern match function. See m//, s///, and tr/// for more info.


Testing

 

Primarily for Numeric Comparison

== TRUE if the left argument is numerically equal to the right argument; otherwise FALSE.
!= TRUE if the left argument is numerically not equal to the right argument; otherwise FALSE
< TRUE if the left argument is numerically less than the right argument; otherwise FALSE
> TRUE if the left argument is numerically greater than the right argument; otherwise FALSE
<= TRUE if the left argument is numerically less than or equal to the right argument; otherwise FALSE
>= TRUE if the left argument is numerically greater than or equal to the right argument; otherwise FALSE
<=> returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument

 

Primarily for String and Character Comparison

eq returns TRUE if the left argument is stringwise equal to the right argument; otherwise FALSE
ne returns TRUE if the left argument is stringwise not equal to the right argument; otherwise FALSE
lt returns TRUE if the left argument is stringwise less than the right argument; otherwise FALSE
gt returns TRUE if the left argument is stringwise greater than the right argument; otherwise FALSE
le returns TRUE if the left argument is stringwise less than or equal to the right argument; otherwise FALSE
ge returns TRUE if the left argument is stringwise greater than or equal to the right argument; otherwise FALSE
cmp returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument

Boolean Expressions

You can also use logical AND, OR and NOT to create more complex expressions:

($a && $b) Are $a AND $b TRUE ?
($a || $b) Is either $a OR $b TRUE ?
!($a) Is $a FALSE ?


 

Important Perl Functions

Any function in the list below may be used either with or without parentheses around its arguments. (The syntax descriptions omit the parentheses.) If you use the parentheses, the simple (but occasionally surprising) rule is this: It LOOKS like a function, therefore it IS a function, and precedence doesn't matter. Otherwise it's a list operator or unary operator, and precedence does matter.

Input and Output

print - output a list to the screen or a file

SYNOPSIS

print FILEHANDLE LIST
print LIST


DESCRIPTION

Used to output a string or a comma-separated list of strings to the screen, or to a file specified by FILEHANDLE. If FILEHANDLE is omitted, prints by default to the screen (standard output). FILEHANDLE may also be replaced by a scalar variable containing the name of the filehandle. For more information on specifying files via FILEHANDLE see the open function.


EXAMPLES

#
# Print Larry's Age
#
$age = "old";
print "Larry is ", $age, "\n";

#
# write something to a file
#
open(OUTFILE, "something.txt");
print OUTFILE, "Something";
close(OUTFILE);

open - open a file

SYNOPSIS

open FILEHANDLE, FILENAME



DESCRIPTION

Opens the file whose filename is given by FILENAME, and associates it with FILEHANDLE.

If the filename is preceded by < or nothing, the file is opened for input. If the filename begins with >, the file is opened for output, being created if necessary. If the filename begins with >>, the file is opened for appending, again being created if necessary.



EXAMPLES

#
# Open file data.txt
# 
$file='data.txt';
open(DATA, $file);     # Open for input
open(DATA, ">$file");  # Open for output
open(DATA, ">>$file"); # Open for appending
open(DATA, "<$file");  # Also open for input

#
# read from a file
#
$file = 'text.txt';
open(TEXT, $file); # Open for input
@lines = <TEXT>;   # Put lines of text into array @lines
close(TEXT);       # Close the file

#
# write something to a file
#
open(OUTFILE, "something.txt");
print OUTFILE, "Something";
close(OUTFILE); 

close - close a file

SYNOPSIS

close FILEHANDLE
close



DESCRIPTION

Closes the file associated with the file handle, returning TRUE if successful. If the argument is omitted the currently selected filehandle is closed.



EXAMPLE

#
# Print something to file
# 
open(OUTFILE, "Info.txt");
print OUTFILE, "Something";
close(OUTFILE); 

 

String Functions

length - return the number of bytes in a string

SYNOPSIS
length EXPR


DESCRIPTION

Returns the length in bytes of the value of EXPR.


EXAMPLE

#
# Print the length of a string
#
$str="writers";
print $str, " is ", length($str), " characters.";

 

reverse - reverse a string or a list

SYNOPSIS

reverse STRING
reverse LIST


DESCRIPTION

In list context, returns a list value consisting of the elements of LIST in the opposite order. In scalar context, concatenates the elements of LIST, and returns a string value consisting of those bytes, but in the opposite order.


EXAMPLE

#
# Print a string backwards
#
$str="writers";
print reverse($str);    # Prints sretirw

 

substr - get or alter a portion of a string


SYNOPSIS

substr EXPR,OFFSET,LEN,REPLACEMENT
substr EXPR,OFFSET,LEN
substr EXPR,OFFSET


DESCRIPTION

Extracts a substring out of EXPR and returns it. First character is at offset 0. If OFFSET is negative, starts that far from the end of the string. If LEN is omitted, returns everything to the end of the string. If LEN is negative, leaves that many characters off the end of the string.

If you specify a substring that is partly outside the string, the part within the string is returned. If the substring is totally outside the string a warning is produced.

Specifying the replacement string as the 4th argument allows you to replace parts of the EXPR and return what was there before in one operation.


EXAMPLE

 


 

index - left-to-right substring search

SYNOPSIS

index STR, SUBSTR, POSITION
index STR, SUBSTR


DESCRIPTION

Returns the position of the first occurrence of SUBSTR in STR. If POSITION is specified, returns the first occurrence at or after that position.


EXAMPLE


      


 

rindex - right-to-left substring search

SYNOPSIS

rindex STR,SUBSTR,POSITION
rindex STR,SUBSTR


DESCRIPTION

Works just like index except that it returns the position of the LAST occurrence of SUBSTR in STR. If POSITION is specified, returns the last occurrence at or before that position.


EXAMPLE

see index


 

split - split up a string using a regexp delimiter

SYNOPSIS

split /PATTERN/,EXPR,LIMIT


DESCRIPTION

Splits a string into an array of strings, and returns it. By default, empty leading fields are preserved, and empty trailing ones are deleted.


EXAMPLE

split(/([,-])/, "1-10,20", 3);

produces the list value (1, '-', 10, ',', 20)


 

join - join a list into a string using a separator

SYNOPSIS

join EXPR,LIST


DESCRIPTION

Joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns the string.



EXAMPLE

 

#
# Print h:i:t:h:e:r:e
#
print join(':', split(/ */, 'hi there'));

Regular Expression Functions

m// - match a string with a regular expression pattern

SYNOPSIS

m/PATTERN/cgimosx


DESCRIPTION

The match operator. Searches a string for a pattern match, and in a scalar context returns TRUE or FALSE. Specify a string to perform the match on via the =~ operator.


OPTIONS

c - Do not reset search position on a failed match when /g is in effect.
g - Match globally, i.e., find all occurrences.
i - Do case-insensitive pattern matching.
m - Treat string as multiple lines.
o - Compile pattern only once.
s - Treat string as single line.
x - Use extended regular expressions.


EXAMPLES

$text = "Drink english tea.";
#
# Does text contain English?
#
($text =~ m/English/)    # FALSE
($text =~ m/[eE]nglish/) # TRUE
($text =~ m/English/i)   # TRUE

 

s/// - replace a pattern with a string

SYNOPSIS

s/PATTERN/REPLACEMENT/egimosx


DESCRIPTION

The substitution operator. Searches a string for a pattern, and if found, replaces that pattern with the replacement text. Specify a string to perform the match on via the =~ operator.


OPTIONS

c - Do not reset search position on a failed match when /g is in effect.
g - Match globally, i.e., find all occurrences.
i - Do case-insensitive pattern matching.
m - Treat string as multiple lines.
o - Compile pattern only once.
s - Treat string as single line.
x - Use extended regular expressions.


EXAMPLES

$text = "Drink english tea.";
#
# Drink French coffee
#
$text =~ s/English/French/i;
$text =~ s/tea/coffee/;

 

tr/// - transliterate a string

SYNOPSIS

tr/SEARCHLIST/REPLACEMENTLIST/cds


DESCRIPTION

The transliteration operator. Transliterates all occurrences of the characters found in the search list with the corresponding character in the replacement list. It returns the number of characters replaced or deleted. A character range may be specified with a hyphen, so tr/A-E/0-4/ does the same replacement as tr/ABCDE/01234/.


OPTIONS

c Complement the SEARCHLIST.
d Delete found but unreplaced characters.
s Squash duplicate replaced characters.


EXAMPLES

# convert $text to lower case
$text =~ tr/A-Z/a-z/;
# count the stars in $sky
$cnt = $sky =~ tr/*/*/;

Functions for Lists and Hashes

keys - retrieve list of indices from a hash

SYNOPSIS

keys HASH


DESCRIPTION

Returns a list consisting of all the keys of the named hash. (In a scalar context, returns the number of keys.)


EXAMPLES

# How many keys?
$numvalues = keys %HSH;

# 
# Print the contents of a hash
# in alphbetical order sorted by key
#
foreach $key (sort(keys %ENV)) {
   print $key, '=', $ENV{$key}, "\n";
}

values - return a list of the values in a hash

SYNOPSIS

values HASH


DESCRIPTION

Returns a list consisting of all the values of the named hash. (In a scalar context, returns the number of values.)


EXAMPLES

# How many values?
$numvalues = values %HSH;

# 
# Print the sorted values of a hash
#
foreach $value (sort(values %HSH)) {
    print "$value\n";
}

 

sort - sort a list of values

SYNOPSIS

sort LIST
sort {BLOCK} LIST


DESCRIPTION

Sorts the LIST and returns the sorted list value. If {BLOCK} is omitted, the list is sorted in standard string comparison order. Otherwise {BLOCK} defines the comparison function between the default operands $a and $b. See below for examples on how to change the sort by defining a new comparison.


EXAMPLES

# sort lexically
@articles = sort @files;

# same thing, but with explicit sort routine
@articles = sort {$a cmp $b} @files;

# now case-insensitively
@articles = sort {uc($a) cmp uc($b)} @files;

# same thing in reversed order
@articles = sort {$b cmp $a} @files;

grep - locate elements in a list test true against a given criterion

SYNOPSIS
grep {BLOCK} LIST
grep EXPR, LIST


DESCRIPTION
This is similar in spirit to, but not the same as the unix grep command. In particular, it is not limited to using regular expressions.

Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and returns the list value consisting of those elements for which the expression evaluated to TRUE. In a scalar context, returns the number of times the expression was TRUE.



EXAMPLES

@foo = grep(!/^#/, @bar); # weed out comments

or equivalently,

@foo = grep {!/^#/} @bar; # weed out comments

Numeric Functions

abs - absolute value function
cos
- cosine function
exp
- raise e to a power
int
- get the integer portion of a number
log
- retrieve the natural logarithm for a number
sin
- return the sin of a number
sqrt
- square root function


Subroutines in Perl

To declare subroutines:

sub NAME {BLOCK} # A declaration and a definition.
sub NAME(PROTO) {BLOCK} # ditto, but with prototypes

a prototype allows you to constrain the arguments you may provide the subroutine to a predefined type-list

To call subroutines:

NAME(LIST);
NAME LIST;

Example:

#
#declaration of subroutine max
#
sub max { 
   my $max = shift(@_);
   foreach $foo (@_) {
      $max = $foo if $max < $foo;
   }
   return $max;
}
#
# call max
#
$bestday = max($mon,$tue,$wed,$thu,$fri);

Another Example:

sub maybeset {
   my($key, $value) = @_;
   $Foo{$key} = $value unless $Foo{$key};
}


 

Regular Expressions

A regular expression is a pattern that defines a set of strings to which it will match. In Perl regular expressions are used for the identification or substitution of patterns in text. See the Perl regular expression functions m// and s/// for more information.

Simple Patterns

The simplest form of regular expression is a literal string which will match itself. It should be noted that Perl regular expressions are processed as double quoted strings so the following escape characters can also be used.

escape characters
\t tab
\n newline
\$ the literal $
\@ the literal @
\\ the literal \\
\ escape the meaning of the next character

Metacharacters

Metacharacters are used to broaden the capabilities of a pattern to match multiple strings or in specific locations. The following are recognized:

metacharacters
. Match any character (except newline)
^ Match the beginning of the line
$ Match the end of the line (or before newline at the end)
| Alternation
( ) Grouping
[ ] Character class

The dot . is used in regular expressions as a wildcard character. It will match any single character, this means /a.a/ will match aaa, aba, etc. To facilitate multi-line substitutions, the . character never matches a newline unless you use the /s option with the pattern matching functions, which in effect tells Perl to pretend the string is a single line--even if it isn't.

The ^ character is guaranteed to match at only the beginning of the string, the $ character at only the end (or before the newline at the end). This means that embedded newlines will not be matched by ^ or $. You may, however, wish to treat a string as a multi-line buffer, such that the ^ will match after any newline within the string, and $ will match before any newline. You can do this by using the /m modifier on the pattern matching functions.

The alternation operator | is used to match either what's on its left or right side. You can also use parethesis ( ) to delimit the area affected by the alternation operator. Some examples of alternation:

/he|she|it/
- match he, she, or it
/g(oo|ee)se/ - match goose or geese

Character Classes

A character class is a set of characters of which one will match, like a restricted wildcard. Character classes are defined by placing the desired matching characters within square brackets [ ]. To save on typing Perl you can use a dash (-) to designate a range of characters such as 0-9 or A-Z. Also you can negate a character class by placing a ^ as the first character. A negated character class matches any one character not within the class. Some examples:

/c[aou]t/ - match cat, cot, or cut
/[a-zA-Z][0-9]/ - match a letter followed by a digit
/[^aeiouAEIOU]/ - match a consonant

Perl also provides some predefined character classes. The following can be used in place of their bracketed alternatives:

predefined character classes
\w Match a "word" character [a-zA-Z_0-9]
\W Match a non-word character [^a-zA-Z_0-9]
\s Match a whitespace character [ \t\n\r\f]
\S Match a non-whitespace character [^ \t\n\r\f]
\d Match a digit character [0-9]
\D Match a non-digit character [^0-9]

Quantifiers

To match runs of characters, character classes, and groups a quantifier can be appended. By default, quantified subpatterns are "greedy", that is, they will match as many times as possible while still allowing the rest of the pattern to match. Perl recognizes the following standard quantifiers:

quantifiers
* Match 0 or more times, same as {0,}
+ Match 1 or more times, same as {1,}
? Match 1 or 0 times, same as {0,1}
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times

 

Anchors

Anchors don't match characters, but places of zero-width within a string. The most commonly used are ^ and $ to match the beginning and end of a line, respectively. Perl defines the following:

zero-width assertions
^ Match the beginning of a string (or line with /m option)

$
Match the end of a string (or line with /m option)

\b
Match a word boundary
\B Match a non-(word boundary)
\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end
\z Match only at end of string
\G Match only where previous m//g left off (works only with /g)

A word boundary \b is defined as a spot between two characters that has a \w on one side of it and a \W on the other side of it (in either order), counting the imaginary characters off the beginning and end of the string as matching a \W. To match the actual end of the string, not ignoring newline use \z. The \G assertion can be used to chain global matches (using m//g).