Perl Operators
This document was written by CS 290W TA David Corcoran and was last
modified
11/12/1998 21:33:55
Like other programming languages, Perl supports most well-known operators
such as the following:
+ - * / = += -= *= /=
These are the basic operators that you see in most languages. Perl also
has a few other operators such as the following:
- The Dot Operator (.)
- This allows you to concatenate two strings together into one
string.
# I am a Comment. I start with a pound sign
# and continue until the end of the line.
$sFirstName = "Jim ";
$sLastName = "Fields";
$sFullName = $sFirstName.$sLastName;
This will take the value of $sFirstName and concatenate the value of
$sLastName. Thus, this will give you the $sFullName "Jim Fields".
- Autoincrement and Autodecrement ( ++ -- )
- This allows you increment or decrement the value of a variable.
# Same as $iHours = $iHours + 1
++$iHours;
$iHours++;
# Same as $iHours = $iHours - 1
--$iMinutes;
$iMinutes--;
- The Chop Operator
- This operator removes ("chops off") the last character from a string.
It returns the chopped character.
$sName = "Dave,";
$sGone = chop($sName);
# $sName is "Dave"
# $sGone is ","
- The Chomp Operator
- This is a special version of chop that removes the last character
from a string ONLY if that last character is a newline (\n). It
returns the number of characters removed.
$sName = "Harrison Ford\n";
chomp($sName);
# $sName is "Harrison Ford"
# chomp returns 1 (character removed), but we
# didn't ask for that to be stored anywhere
$sName = "Carrie Fisher";
$iHowMany = chomp($sName);
# $sName is "Carrie Fisher"
# $iHowMany is 0
Chomp is often used for an array of character strings:
@asMotto = ("You\n","can leave\n","your","hat on.\n");
$iHowMany = chomp (@asMotto);
# @asMotto = ("You","can leave","your","hat on.")
# $iHowMany is 3.
- Relational Operators
- Perl has operators that are used in if, unless, while, until, and
for statements (see Block Structures and
Loops). One set of operators works for numeric values. The other
set works for string values.
numeric | string | meaning |
== | eq | equal to |
!= | ne | not equal to |
> | gt | greater than |
>= | ge | greater than or equal to |
< | lt | less than |
<= | le | less than or equal to |
if ( $iAge == $iSubmit )
if ( $sName eq $sLastOne )
if ( $iAge <= $iSubmit )
if ( $sName le $sLastOne )