Chapter 2: Perl Operators - Training Etc

hollowtexicoSoftware and s/w Development

Dec 13, 2013 (3 years and 6 months ago)

90 views

P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-1
Chapter 2:
Perl Operators
1) Introduction..............................................................................................................2-2
2) Table Of Perl Operators..........................................................................................2-3
3) Arithmetic Operators..............................................................................................2-4
4) String Operators......................................................................................................2-5
5) Relational Operators...............................................................................................2-7
6) Logical Operators....................................................................................................2-8
7) Bitwise Operators...................................................................................................2-10
8) Assignment Operators...........................................................................................2-11
9) The Conditional Operator.....................................................................................2-12
10) Range Operator......................................................................................................2-13
11) String Functions.....................................................................................................2-14
12) The eval Function................................................................................................2-17

Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-2
Introduction

Perl has a wide variety of operators. Many of them are
borrowed from C, while others are unique to Perl.

Operators vary according to type. For example, String
equality and numeric equality operators are different.

In the proper context, Perl will convert in accordance with
"mixed" operands. For example:
mixed
1. #!/usr/bin/perl
2.
3. $value = 50;
4. $increment = "10 + 1/2";
5. $value = $value + $increment;
6. print "$value\n"; # prints 60
7.
8. $value = "10" + "20";
9. print "$value\n"; # prints 30
10.
11. $value = $value + eval($increment);
12. print "$value\n"; # prints 40.5


On the next page, you will see the complete operator table
including hierarchy and associativity.
Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-3
Table Of Perl Operators
Operator
Description
Associativity
C
Operator?
( )

[ ] { }
function call
subscript
left to right

y
y,n
++

--
auto increment
auto decrement
NONE

y
y
not !

~
-
logical NOT
bitwise NOT
unary
right to left

y
y
y
**

exponentiation right to left

n
=~

!~
pattern match
pattern not match
left to right

Shell
*

/
%
x
multiply
divide
modulus
repeat
left to right

y
y
y
n
+

-
.
add
subtract
concatenate
left to right

y
y
n
<<

>>
bitwise left shift
bitwise right shift
left to right

y
y
-d -r -x etc.

file test operators NONE

Shell
< <= > >=
lt le gt ge

numeric relational
string relational
NONE

y,y,y,y
n,n,n,n
==
!= <=>

eq
ne cmp
numeric equal
numeric not equal
string equal
string not equal
NONE

y
y,n
n
n,n
&

bitwise AND left to right

y
|

^
bitwise OR
exclusive OR
left to right

y
y
and &&

logical AND left to right

y
or ||

logical OR left to right

y
..

range operator NONE

n
?:

conditional
expression
left to right

y
= += -= etc.

assignment
operators
right to left

y
,

comma operator left to right

y

Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-4
Arithmetic Operators

The usual arithmetic operators:
$a = 5;
$b = 2;
$c = 3;

$d = $a + $b * $c; # $d = 11
$d = $c ** 2; # $d = 9
$d = $b ** 3 ** 2 # $d = 512 (right to left)

Note that the ++ and -- operators are exactly like those
of the C language.
$a = 4;

$b = $a++; # $b = 4, $a = 5
$b = ++$a; # $a = 6, $b = 6
$b = --$a; # $a = 5, $b = 5
$b = $a--; # $b = 5, $a = 4

The modulus (remainder) operator:
$a = 21;
$b = 8;

$c = $a % $b; # $c = 5
Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-5
String Operators

String repetition and string concatenation:
stringops
1. #!/usr/bin/perl
2.
3. while(1)
4. {
5. print "Enter string: ";
6. chop($str = <STDIN>);
7. print "Enter another: ";
8. chop($other = <STDIN>);
9.
10. $str = $str . $other;
11. print "Concatenation is: $str\n";
12.
13. print "Enter repeat factor: ";
14. $factor = <STDIN>;
15.
16. $str = $str x $factor;
17. print "$str\n";
18. }


Sample output:
Enter string: mike
Enter another: joe
Concatenation is: mikejoe
Enter repeat factor: 3
mikejoemikejoemikejoe
^C

Note: The program is terminated by typing Control-C.
Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-6
String Operators

Note also:
careful
1. #!/usr/bin/perl
2.
3. $a = (5 + 2) * 4; # multiplication
4. print "$a\n";
5.
6. $b = (5 + 2) x 4; # repetition
7. print "$b\n";


Output:
28
7777

Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-7
Relational Operators

Relational operators have two different flavors:
Numeric
String
Meaning
> gt
greater than
>= ge
greater than or equal
< lt
less than
<= le
less than or equal
== eq
equal
!= ne
not equal
<=> cmp
signed equality


A relational test generates the value 1 when the
relationship is true and the empty string ("") when false.

The operators <=> and cmp are similar to the C
language strcmp function. They return -1, 0, or 1.
relational
1. #!/usr/bin/perl
2.
3. $a = 5;
4. $b = 10;
5. print $a < $b, "\n"; # prints 1
6. print $a lt $b, "\n"; # prints empty string
7.
8. $x = $a <=> $b; # $x = -1
9. $y = $a <=> $a; # $y = 0
10. $z = $b <=> $a; # $z = 1
11. print "$x, $y, $z\n";
12.
13. $x = "hello";
14. $y = "zebra";
15. print $y cmp $x, "\n"; # prints 1
Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-8
Logical Operators

The and and or operators are to join two simple
conditions to form a compound condition. Logical not
reverses the truth value of a condition (or expression).

The logical operators come in two "flavors":

Symbol
Word
Meaning
! not
Logical not
&& and
Logical and
|| or
Logical or


The and and or operators are "short circuit" operators,
which means that they stop evaluating when they have
determined the truth value of a compound condition.

With logical or, if the first condition is true, then the
second condition will not be evaluated.
if ( $a > $b || $c == $d)
{
...
}


With logical and, if the first condition is false, then the
second condition will not be evaluated.
if ( $a > $b && ($a = $x ))
{
...
}

Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-9
Logical Operators

An example of logical not:
if ( not ($a >= 10 and $a <= 20))
{
print "$a is not between 10 and 20\n";
}


The logical operators can be used in assignments as well:
$x = 10;
$y = 20;

$z = $x >= 0 && $y >= 0; # $z = 1
$z = $x && $y; # $z = 20
$z = $x || $y; # $z = 10


When working with relational and logical operators in Perl,
always remember these fundamental rules:
 Zero (or empty string) is considered false
 Anything else is considered true


Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-10
Bitwise Operators

Perl has a number of operators to manipulate the
individual bits of a numeric value.

$a = 055; # Octal (base 8)
$b = 0x44; # Hexadecimal (base 16)

$a and $b in memory (assume 16 bits):

$a 0 000 000 000 101 101
$b 0 000 000 001 000 100

$a | b 0 000 000 001 101 101 OR

$a & b 0 000 000 000 000 100 AND

$a ^ b 0 000 000 001 101 001 EXCLUSIVE OR

~$a 1 111 111 111 010 010 COMPLEMENT

$a >> 3 0 000 000 000 000 101 RIGHT SHIFT

$b << 3 0 000 001 000 100 000 LEFT SHIFT


Bitwise or, and, and exclusive or combine the
corresponding bits of the two operands according to the
rules in the table below.

Op 1
Op 2
|
&
^
0 0 0 0 0
0 1 1 0 1
1 0 1 0 1
1 1 1 1 0
Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-11
Assignment Operators

Any binary operator can be written using the assignment
operator:
 ARITHMETIC
$x = 10;
$x = $x + 5; $x += 5;
$x = $x / 2; $x /= 2;

 EXPONENTIATION
$x = $x ** 5; $x **= 5;

 STRING
$a = "alpha";
$b = "bet";
$a = $a . $b; $a .= $b;
$a = $a x 3; $a x= 3;

 BIT WISE
$x = $x << 3; $x <<= 3;
$x = $x | 077; $x |= 077;
$x = $x & 077; $x &= 077;
Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-12
The Conditional Operator

Perl uses the conditional operator that is familiar to C
programmers. You can think of this operator as a short
version of the if-else construct.
$max = $a > $b ? $a : $b;

print ($c%2 == 0 ? "even " : "odd ");

$s1 = $a ** 2;
$s2 = $b ** 2;
$h = $c ** 2;
print "Sides squared: $s1, $s2, $h\n";

$ans = $s1 + $s2 == $h ? "Is" : "Is not";
print "$ans a right triangle\n";

Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-13
Range Operator

The range operator (..) has several distinct uses.
 Iterating through a loop a specific number a times
$sum=0;
foreach $item ( 10 .. 20 )
{
$sum += $item;
}
print "$sum\n";

 Grabbing a range of lines from a file
$low = 25;
$high = 50;
if ($low == $. .. $high == $.)
{
print; # print lines 25 .. 50
}

 Checking against $. is implied if constants are given
if (25 .. 50) # print lines 25 thru 50
{
print;
}

 Also good for array slices (discussed in a later chapter)
@slice=@values[2 .. 5]; # 3rd-6th
Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-14
String Functions

In addition to the concatenation and repetition operators,
Perl has many functions that operate on strings.

The length function returns the length of a string.
$string = "mike smith\n";
$len = length($string); # len = 11

The index function returns the first position (0-based) of
a string where a substring is found, or -1 if the substring
is not found.
$s = "if you don't succeed, try try again";
$pos1 = index($s, "try"); # pos1 = 22
$pos2 = index($s, "Try"); # pos2 = -1


The index function can have an optional third argument
which specifies how much to skip in the string before you
start searching.
$pos3 = index($s, "try", 23); # pos = 26

The substr function returns a substring of length $n
starting at position $pos.
$pos = 3;
$n = 6
$sub = substr($s, $pos, $n);
print "$sub\n"; # you do
Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-15
String Functions

When used on the left-hand side of an assignment
statement, substr can be used to alter a string.
substrings
1. #!/usr/bin/perl
2.
3. print "-> starting at 0\n";
4. for ($i = 0; $i < 3; $i++)
5. {
6. $line = "Perl is fun";
7. substr ($line, 0, $i) = "12";
8. print "$line\n";
9. }
10. # Output is:
11. # 12Perl is fun
12. # 12erl is fun
13. # 12rl is fun
14.
15. print "-> starting at 1\n";
16. for ($i = 0; $i < 3; $i++)
17. {
18. $line = "Perl is fun";
19. substr($line, 1, $i) = "12";
20. print "$line\n";
21. }
22. # Output is:
23. # P12erl is fun
24. # P12rl is fun
25. # P12l is fun
26.
27. # Continued on next page
Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-16
String Functions
substrings (continued)
28. print "-> starting at -3\n";
29. for ($i = 0; $i < 3; $i++)
30. {
31. $line = "Perl is fun";
32. substr($line,-3,$i) = "12";
33. print "$line\n";
34. }
35. # Output is:
36. # Perl is 12fun
37. # Perl is 12un
38. # Perl is 12n


Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-17
The eval Function

Occasionally you may have the need to build Perl scripts
inside of a Perl script. One use of eval is to execute
these scripts from inside the containing script. Here is an
example of a one-line script.
$a = 10;
$b = 20;
$str = '$a + $b';
$c = eval $str;
print "$c"; # prints 30;


The evaluated expression (i.e., the "little program") can be
as many lines as you wish.
$str = '$a = 4; $b = 3; sqrt($a**2 + $b**2)';
$c = eval $str;
print "$c"; # prints 5;


If the "program" being evaluated has a syntax error, then
Perl loads the variable $@ with the error message. Below
is a calculator program that evaluates Perl expressions
entered at the keyboard.

calc
1. #!/usr/bin/perl
2.
3. while (<STDIN>)
4. {
5. print eval "$_", "\n";
6. print $@ if $@; # $@ is set to error
7. # message from eval
8. }
Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-18
The eval Function

You can use eval to "build" variables dynamically.
evaltest
1. #!/usr/bin/perl
2.
3. $a = 10;
4. $b = 20;
5. $x = '$z = $a + $b';
6.
7. print "$x\n";
8. print eval($x), "\n";
9. print "$z\n";


Output:
$z = $a + $b
30
30


You can also use eval to evaluate a block of code. Many
Perl programmers perform error checking in this way.
$a = 10;
chop($b = <STDIN>);

eval
{
$c = $a / $b;
}

if ($@)
{
print $@;
exit; # terminate the script
}
Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-19
Exercises

1. Write a program which reads in three numbers and
checks to see if the last one is an odd number between
the first two.
2. Write a program that displays the sum of the following
integers. (Hint: Use the range operator.)
1 through 100 and 201 through 300

3. Write a program that prompts the user for two strings.
Print the position number within the first string where the
second
instance of the second string occurs.
Sample output:
Enter a string: hello there, this is a string
Enter a substring: th
The second occurrence of (th) is at position 13

4. Write a program which reads a positive number and then
prints the binary representation of the number.
Sample output:
Enter a number: 58
111010

5. Write a program that inputs a string and determines if it is
a palindrome or not. (Hint: use the substr function.)
Evaluation
Copy
Evaluation
Copy




P
ERL
P
ROGRAMMING
C
HAPTER
2:

P
ERL
O
PERATORS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
2-20
Exercises
6. Write a program to compute the amount of the monthly
payment on a loan based on the formula below.
M = P * ( J / ( 1 - (( 1 + J) ** - N)))

where

M = Monthly payment
P = Loan amount
I = Interest rate
J = I / (12 x 100)
N = Number of months over which loan is amortized


Test your program by computing the monthly payment for
a $200000 mortgage at 7.5% over 30 years.
 The result should be 1398.43.


Evaluation
Copy
Evaluation
Copy