An operator manipulates data objects called operands. The operands can be either strings, numbers, or combinations of both. Data objects can be manipulated in a number of ways by the large numbers of operators provided by Perl. Most of the Perl operators are borrowed from C, although Perl has some additional operators of its own. In Perl 5 you can use functions as operators if the parantheses are omitted.
Operator | Example | Meaning |
= | $var = 5; | Assign 5 to $var |
+= | $var += 3; | Add 3 to $var and assigns result to $var |
-= | $var -= 7; | Substract 7 from $var and assigns result to $var |
*= | $var *= 4; | Multiply $var by 4 and assigns result to $var |
/= | $var /= 2; | Divide $var by 2 and assigns result to $var |
**= | $var **= 2; | Square $var and assigns result to $var |
%= | $var %= 3; | Divide $var by 3 and assign reminder to $var |
.= | $str .= "ing"; | Concatenate "ing" to $srt and assign result to $str |
x= | $str x= 20; | Repeat value of $str 20 times and assign result to $str |
Numeric Operator |
String Operator |
Meaning |
> | gt | Greater than |
>= | ge | Greater than or equal to |
< | lt | Less than |
<= | le | Less than or equal to |
Numeric Operator |
String Operator |
Returns |
== | eq | true if the operators are equal |
!= | ne | true if the the operators are not equal |
<=> | cmp | 1 if first operator is greater than second one, 0 if they are equal, and -1 if first operator is less than the second one. |
Operator | Example | Meaning |
+ | $x + $y | Addition |
- | $x - $y | Substraction |
* | $x * $y | Multiplication |
/ | $x / $y | Division |
% | $x % $y | Modulus |
** | $x ** $y | Exponential |
++ | $x++ or ++$x | Post or Pre-increment; equivalent to $x = $x + 1 |
-- | $x-- or --$y | Post or Pre-decrement; equivalent to $x = $x - 1 |
Examples: Assume that at the beginning of each of the following examples $x=0 and $y=0.
Example | Equivalence Result |
$y = ++ $x; | at the end, $y = 1 and $x = 1. Equivalent to $x = $x + 1; $y = $x; |
$y = $x ++; | at the end, $y = 0 and $x = 1. Equivalent to $y = $x; $x = $x + 1; |
$y = -- $x; | at the end, $y = -1 and $x = -1. Equivalent to $x = $x - 1; $y = $x; |
$y = $x --; | at the end, $y = 0 and $x = -1. Equivalent to $y = $x; $x = $x - 1; |
Example | Meaning |
$str1 . $str2 | Concatenate $str1 and $str2. |
$str1 x $num1 | Concatenate $str1, $num1 times. |
substr($str1, $offset,$len) | Substring of $str1 at $offset for $len bytes (characters). |
index($str1,$str2) | Byte (character) offset of $str2 in $str1. |
rindex($str1,$str2) rindex($str1,$str2,$pozition) |
Returns the pozition of the last occurence of $str2 in $str1. If $pozition is specified, start looking there. If $position is not specified, start at the end of $str1. |
length($str) | Returns the length in characters of the string. |
chr(NUMBER) chr($num) |
Returns the character represented by NUMBER or $num in the ASCII set. For example, chr(65) is 'A' |
lc($str) | Returns the lowercase version of $str. |
uc($str) | Returns the uppercase version of $str. |
Example:
$message="Welcome to my web site";
print substr($message,14,3),"\n";
print index($message," "),"\n";
print rindex($message," "),"\n";
print rindex($message," ",12),"\n";
print substr($message,index($message,"my")),"\n";
substr($message,0,0)="Hello and ";
print "$message \n";
substr($message,10,1)="w";
substr($message,-1,1)="e!";
print "$message\n";
print "uc($message) = ",uc($message),"\n";
print "lc($message) = ",lc($message),"\n";
print "length($message) = ",length($message),"\n";
Question: What is the output of this program?
There are 3 main operators that ease our work with strings. They are used to change the content of strings or to indentify various substrings. These operators are tr///, s///, and m//. These operators work on the $_ variable unless you use the =~ operator. You can see the difference in the examples below.
Example.
tr/A-Z/a-z/; # operates on $_
$str1 =~ tr/A-Z/a-z/; # operates on $str1
This command operates on a hole string at one, converting each individual character in turn. The example above does an uppercase to lowecase translation. To better understand what tr/// is doing, lets call the text between the first two slashes the left hand side (lhs) and that between the last to slashes the right hand side (rhs). Each side represents a set of characters, and each character on the lhs is replaced with the corresponding character from the rhs. The dash (-) is not another character; in this context it acts to expand the A-Z to fill in all the missing characters from A to Z, and likewise for a-z. tr/// leaves characters not found in lhs alone. Thus, in the previous example, nothing happens to punctuation, numbers or characters which are already in lowercase.
Example.
$mystring="Doing well";
$mystring =~ tr/ngwi/r bo/;
print "$mystring \n";
will output
Door bell
If the number of characters in the lhs is greater than the number of characters in the rhs, the last element of the rhs will use for all unmatched characters from lhs. If the number of characters in the rhs is greater than the number of characters in the lhs, all unmatched characters from rhs will be ignored.
This command is related to tr/// but instead of replacing each character in the lhs with the corresponding one from the rhs it searches through the query variable trying to find a match to the whole lhs and then replaces that with the rhs. For example
$weather = "A rainy day.";
$weather =~ s/rainy/sunny/;
print "$weather \n";
will print A sunny day.
Substitutions only occur if the string on the left can be matched. One can say that you can do that easily using the string functions index and substr. This is true, but with those functions you can not do pattern-matching. You can declare the lhs to be a patter, and then replace any occurance with the rhs. The most unrestricted character in patter definition in Perl is the period (.). It will match any single character, except a newline. For example
$weather = "Humidity: 80%";
$weather =~ s/..%/5%/;
print "$weather \n";
will print Humidity: 5%. Note that the length of the string on the lhs and rhs don't need to be the same, since the whole left is replaced with the whole right. What happens if instead of 80% we have 9% in the $weather scalar? Well, since it has to match 2 characters, the space before 9% will be also replace, thus
$weather = "Humidity: 9%";
$weather =~ s/..%/5%/;
print "$weather \n";
will print Humidity:5%.
There are other metacharacters that we can use to define patterns. \d will match anysingle digit, \w will match any "word" character (a-z, A-Z) and \s will match any white space. There are also antonyms like \D, \W, \S which match anything but digits, words and spaces, respectively. For example
$string1 = " fog log frog !og";
$string2 = $string1;
$string1 =~ s/\S\wog/dog/;
$string2 =~ s/..og/dog/;
print "$string1 \n $string2 \n";
will print
fog log dog !og
fogdog frog !og
To match a variable number of characters, we use the asterisk (*). It modifies the previous character or metacharacter in the patter to match zero or more characters. For example, do*g will match dog, dg, doog, and dooooooooooog. The expression .* matches any string of any length and \d* mathces zero or more digits. Thus, goind back to our Humidity example, \d*% will alwys prin Humidity: 5% no matter how much is the actual humidity: 9%, 80% or 100%. A modifier similar to * is the question mark (?), which matches zero or one occurences of the character. To use any of the metacharacters (., *, or ?) to identify the character it represents, we have to use a backslash before it. Thus \. will identify a period, \\ matches asingle backslash, \? matches a question mark, and \* matches an asterisk.
Example.
$address = "mainline.brynmawr.edu";
$address =~ s/.*\.//;
print "$address\n";
Question: What is the output of this program?
Instead of using the predefined wildcard you can define your own ones. For example, [abc] will match any character in the set between the square brackets (this counts as one character). To make a wildcard that matches "everything except" your list, then use the carat (^) character. Thus [^nN] will match everything except n or N.
We can add additional parametersto the s/// operator. Putting a g after the last slash will cause all occurences of the lhs to be replaced by the rhs rather than just the first one, and i makes the pattern matching case-insensitive.
Example.
$string1 = " foG log frog !og";
$string2 = $string1;
$string3 = $string1;
$string1 =~ s/\S\w*og/dog/;
$string2 =~ s/\S\w*og/dog/g;
$string3 =~ s/\S\w*og/dog/gi;
print "$string1 \n$string2 \n$string3\n";
will print
foG dog frog !og
foG dog dog dog
dog dog dog dog
This operator works like the s/// operator, but it just matches the lhs in the operand. It returns true if a match was made. All what we presented for s/// works for m// operator. Moreover, m can be omitted, so we can write just
$weather = "It's pretty cloudy outside.";
if ($weather =~ /cloudy/) {
print "You'll better stay home!\n";
}
The chop function chops off the last character in each scalar of the list (@array). The chomp function removes only the last character if it is a newline. For example
@list=("string\n",100,"text","20");
chop(@list);
print "@list";
will print string 10 tex 2 while
@list=("string\n",100,"text","20");
chomp(@list);
print "@list";
will print string 100 text 20.
The grep function evaluates the expression (EXPR) for each element in the list (@array). The return is either another array consisting those elements for which the expression evaluated is true or a scalar that represents the number of times the expression was true. For example
@list=("computer","printer","monitor","driver");
$count=grep(/er/i,@list);
@found=grep(/er/i,@list);
will store 3 in $count and ("computer","printer","driver") in $found.
The join function joins elements of an array into a single string and separates each element of the array with a given delimiter, which can be a character or a string. This function is the oposit of the split function.
@list=("My","name","is","Bogdan");
$string=join(" ",@list);
$print "$string.\n";
will print My name is Bogdan.
The pop function pops off the last element of an array and returns it. The array size is decreased by one.
@list=("computer","printer","monitor","driver");
$lastelement=pop(@list);
print "Last element was: $lastelement\n";
print "New list is: @list\n";
will print
Last element was: driver
New list is: computer printer monitor
The push function pushes values onto the end of an array, increasing the length of the array.
@list=("computer","printer","monitor","driver");
push(@list,"keyboard");
push(@list,"mouse","floppy disk","hard drive");
Now @list contains all the elements presented above.
The shift function shifts off and returns the first element of an array, decreasing the size by one element.Works similar to pop, but instead of operating at the end of the array, it operates at the beginning.
The splice function removes and replaces elements in an array. OFFSET is the starting position where elements are to be removed. LENGTH is the number of items from the OFFSET position to be removed. LIST consists of new elements that are to replace the old ones. If LENGTH and LIST are ommited, splice will remove all the elements from OFFSET to the end of the string.
@list=("computer","printer","monitor","driver");
@out=splice(@list,1,2,"keyboard");
will store ("computer","keyboard","driver") in @list.
The split function splits up STRING by some DELIMITER (white space by default) and returns an array. If the DELIMITER doesn't match a delimiter, split returns the original string. You can specify more than one delimiter using the regular expression metacharacter, []. For example, [ +\t:] represents zero or more spaces, or a tab, or a colon. The LIMIT soecifies the number of fields that can be split. If there are mre than LIMIT fields, the remaining fields will all be part of the last one.
$string=" here there and everywhere ";
@list1=split(' ',$string);
@list2=split(' ',$string,2);
print "First element in \@list1 is $list1[0]\n";
print "Second element in \@list1 is $list1[1]\n";
print "First element in \@list2 is $list2[0]\n";
print "Second element in \@list2 is $list2[1]\n";
will print
First element in @list1 is here
Second element in @list1 is there
First element in @list2 is here
Second element in @list2 is there and everywhere
The sort function sorts and returns a sorted array, If SUBROUTINE is ommited, the sort is in a string comparison order. If SUBROUTINE is specified, the first argument to sort is the name of the subroutine followed by a list of integers. The subroutine returns an integer less than, equal to, or greater than 0. The values are passed to the subroutine by reference and are received by the special variables $a and $b, not the normal @_ array.
@colors=("yellow","blue","red","green");
@colors_sort=sort(@colors);
print "@colors_sort\n";
@numbers=(10,22,-15,3);
@numbers_sort=sort(numeric @numbers);
print "@numbers_sort\n";
sub numeric {
$a<=>$b
}
will output
blue green red yellow
-15 3 10 22
Note: There is no comma between subroutine name and the list when calling the sort function.
The reverse function reverses the elements in an array, so that if it was descending, now it is ascending. Always the first element becomes the last one, and viceversa. Reverse does not compare elements in an array, just changes the order.
The unshift function adds elements from the LIST at the beginning of the array. It is simmilar to push, but works at the beginning of the string rather then at the end.
The keys function returns an array whose elements are the keys of an associative array.The values function returns an array whose elements are the values of an associative array.
%colleges = ('BMC'=>'Bryn Mawr College',
'HC'=>'Haverford
College',
'SC'=>'Swarthmore
College');
@colleges_keys= keys(%colleges);
@colleges_values=values(%colleges);
print "The keys are: @colleges_keys\n";
print "The values are: @colleges_values\n";
will output
The keys are: BMC HC SC
The values are: Bryn Mawr College Haverford College Swarthmore College
The each function returns, in random order, a two element array whose elements are the key and the corresponding value of an associative array.
%colleges = ('BMC'=>'Bryn Mawr College',
'HC'=>'Haverford
College',
'SC'=>'Swarthmore
College');
while (($k,$v)=each(%colleges)) {
print "$k = $v\n";
}
will output
BMC = Bryn Mawr College
HC = Haverford College
SC = Swarthmore College
The delete function deletes a value from an associative array. The deleted values is returned if successful. For example, to completely delete the elements of an associative array we can use the following code:
%colleges = ('BMC'=>'Bryn Mawr College',
'HC'=>'Haverford
College',
'SC'=>'Swarthmore
College');
foreach $k (keys(%colleges)) {
delete $colleges{$k};
}