Getting Started
Introduction
Perl IDEs
History
Advice
Tools
Mini-Tutorial
Tutorial
Code Snippets

Resources
Top Sites
More Tutorials
Books
Magazines
Articles
NewsLetters
Mailing Lists
NewsGroups
Forums
User Groups
Talk Shows
Blogs
Clothing

GBIC >> Perl >> Information Center Tutorials >> Operators

Perl Information Center Tutorials - Operators
These tutorials were written to help you get a quick, but thorough, understanding of Perl - the scope of the language as well as it's specific capabilities.

Beginners Built-In Functions     Advanced CGI Applications

Operators
If there's one thing Perl has plenty of, it's operators. Here's a compact listing of the operators Perl supports. This tutorial breaks these into common groups for discussion.

     +   +=     and  &  &&     <   lt      ''         =~     ->
     -   -=     or   |  ||     >   gt      ""         !~     =>
     *   *=     xor  ^         <=  le      ``         #      <<
     /   /=     not  !         >=  ge      q/ /       ..     >>
     %   %=                    ==  eq      qq/ /      .      <>
     **  **=                   !=  ne      qr/ /      .=     \
     ++  &=                    <=> cmp     qx/ /      x      ?:
     --  |=                                qw/ /      x=
     =   ^=
         <<=
         >>=
         &&=
         \\=

Basic Arithmetic
The + - * / % operators perform as expected. However Perl uses the ** operator (instead of ^, as most languages do) for exponentiation. Perl supports the C-style ++ and -- operators for incrementing/decrementing by 1.

    =     $x=2          # assigns $x the value of 2
    +     $x = $x + 1   # add
    -     $x = $x - 1   # subtract
    *     $x = $x * 2   # multiply
    /     $x = $x / 2   # divide
    %     $x%5          # modulus (whole number remainder of division)
    **    $x = $x**2    # raises $x to the power of 2
    ++    $x++          # increments $x by 1
    --    $x--          # decrements $x by 1

The ++ and -- operators can be placed on either side of a variable. When used as a single line of code the position does not matter. But when used within an expression, the position of the operators determines whether the new or old value of the variable will be used in evaluating the expression. The following example demonstrates how these operators work.

     $x++    # uses current value of $x in expression, then increments
     $x--    # uses current value of $x in expression, then decrements
     ++$x    # increments first, then uses new value of $x in expression
     --$x    # decrements first, then uses new value of $x in expression
     print $x++   # prints $x, then increments $x by 1
     print ++$x   # increments $x by 1, then prints $x

String Operators
Perl uses the . and x operators to operate on strings.

     .      string concatenation     # "a"."b" yields "ab"
     x      string multiplier        # "ab" x 3 yields "ababab"

Logical Operators
Logical operators test to see if expressions or values are true or false. In Perl the values 0, "0", '', "", (), and undef are all false. All other values are true.

Here are the logical operators supported by Perl.

       and     &     &&       # all 3 columns perform 'and'
       or      |     ||       # all 3 columns perform 'or' 
       xor     ^              # the two columns perform 'xor'
       not     !              # the two columns perform 'not'

&& and || are short-circuit operators, meaning that && will not execute the second expression if the first expression is false. And || will will not execute the second expression if the first expression is true.

Relational/Equality Operators
In Perl, strings comparison operators are not the same as number comparison operators. In the table below the Number and String comparison operators are shown. Note that Perl will allow you to use any comparison operator against two variables but will convert the content to match the type of comparison operator - without raising an exception!

    Number  String    Comparison
      ==      eq     equal
      !=      ne     not equal
      <       lt     less than
      >       gt     greater than
      <=      le     less than or equal to
      >=      ge     greater than or equal to
      <=>     cmp    trinary comparions

As a memory aide, just remember that string comparison operators are comprised of strings (letters).

The two equality operators, <=> and cmp, give trinary results - providing 1, -1, or 0 depending on the comparison of two values. These are particularly valuable with the Perl sort function.

     <=>   returns 1, -1, 0, using comparison below on values as numbers
     cmp   returns 1, -1, 0, using comparison below on values as strings.

          * 1 if $a is greater than $b
          * -1 if $b is greater than $a
          * 0 if $a and $b are equal

     $a=5; $b=7
     print ($a <=> $b);      # prints -1
     $a="dog"; $b="cow"
     print ($a cmp $b);      # prints 1

See the sort tutorial for additional usage information.

Miscellaneous

     =~     binds string expression to a pattern match
     !~     logical negation of =~ 
     ~      arithmetic/bitwise negation
     ..     range operator
     ?:     flow control 
     =>     alternative separator for comman 
     <>     filehandle
     ->     returns value at variable reference (dereferencing)
     \      references variable storage location
     <<     shift left
     >>     shift right

Compound Operators
To simplify coding, Perl also offer the ability to combine operators, as in the following code example:

     +=     $x+=5      # same as $x = $x+5
     -=     $x-=5      # same as $x = $x-5
     *=     $x*=5      # same as $x = $x*5
     /=     $x/=5      # same as $x = $x/5
     %=     $x%=5      # same as $x = $x%5
     **=    $x**=5     # same as $x = $x**5
     .=     $x.="a"    # same as $x = $x . "a"
     x=     $a x= 10   # sames as $a = $a x 10
     &=
     |=
     ^=
     <<=
     >>=
     &&=
     \\=

Quote Operators
Perl uses single and double quotes more like operators, in that they act on the quote content by performing interpolation and matching. Perl also allows programmers to define their own quote characters to replace the single/double quotes. When replacing the quote characters (single or double), the q, qq, qx, and qw operators are used to initiate the replacement. In the example below, the / / characters are used to surround quoted strings, but any Perl allows the programmer to select any character to act as the quote strings.

  ''       single quotes, no interpolation except \' and \\)
  ""       double quotes, interpolation
  ``       backquotes, interpolation, passes command to OS, returns stdout
  q/ /     same as single quotes, no interpolation except \' and \\
  qq/ /    same as double quotes, interpolation
  qr/ /    returns compiled form of regex
  qx/ /    same as backquotes, interpolation
  qw/ /    creates list of words separated by whitespace

The quote characters used here (/ /) can be any character the programmer chooses, such as {} or [].

Here Document - Printing Multiline Quotes
The << operator is used by Perl to simplify printing multiple lines of text without having to print each line and without having to use quotes on very line. This is called here document quoting.

The << operator is particularly useful in creating dynamic web pages.

Here's how it looks:

     print <<bigtext;        # print <<'bigtext' stops interpolation
     line one
     line two
     line three
     bigtext                       # bigtext by itself, no semicolon

The string 'bigtext' names the quote and can be any word defined by the programmer. The print statement will print everything down to the line where the name word is found on a line by itself, with no semicolon.

The word must be on a line by itself and cannot be the last line in the Perl script (if it is, simply add a return after the word). There is no semicolon after the line containing the word.

By default, here document quoting acts like double quotes, with interpolation. The word can be surrounded by other quote types (such as single quotes) to change that behavior.

If you have suggestions or corrections, please let me know.