Session 5 Operators in PerlRAM N SANGWAN
WWW.RNSANGWAN.COM
1
Arithmetic
• Perl operators are the same as in C and Java
• these are only good for numbers
• but beware:$b = "3" + "5";
print $b, "\n"; # prints the number 8
• if a string can be interpreted as a number givenarithmetic operators, it will be
• what is the value of $b?:$b = "3" + "five" + 6?
• Perl semantics can be tricky to completely understand
Operators - Maths
• The usual suspects: + - * / %
$total = $subtotal * (1 + $tax / 100.0);
• Exponentiation: **
$cube = $value ** 3;
$cuberoot = $value ** (1.0/3);
• Bit-level Operations
left-shift: << $val = $bits << 1;
right-shift: >>$val = $bits >> 8;
Operators - Assignments
• As usual: = += -= *= /= **= <<= >>=$value *= 5;
$longword <<= 16;
• Increment: ++$counter++
++$counter
• Decrement: --$num_tries--
--$num_tries
Numeric Operators
Operator Associativity
++ -- none
unary - right
** right
* / % left
binary + - left
++ and – have the highest precedence.
Arithmetic in Perl
6
$a = 1 + 2; # Add 1 and 2 and store in $a
$a = 3 - 4; # Subtract 4 from 3 and store in $a
$a = 5 * 6; # Multiply 5 and 6
$a = 7 / 8; # Divide 7 by 8 to give 0.875
$a = 9 ** 10; # Nine to the power of 10, that is, 910
$a = 5 % 2; # Remainder of 5 divided by 2
++$a; # Increment $a and then return it
$a++; # Return $a and then increment it
--$a; # Decrement $a and then return it
$a--; # Return $a and then decrement it
Examples
• 4 % 2 → 0
• 5 / 2 → 2.5 (5 and 2 are coerced from integers toreals).
$total++ * 3
$a ** 2
$b / $ c / 2
• Important. The order of evaluation of operands ofoperators is unspecified. This is left for the compiler todecide.• Ex: $x++ * $x--
Operators - Boolean
• Boolean (against bits in each byte)• Usual operators: & |
• Exclusive-or: ^
• Bitwise Negation: ~
$picture = $backgnd & ~$mask | $image;
• Boolean Assignment• &= |= ^=
$picture &= $mask;
Operators-Logical (expressions)
• && And operator
• | | Or operator
• ! Not operator
Operators - Short Circuit Operators
• expr1 && expr2
• expr1 is evaluated.
• expr2 is only evaluated if expr1 was true.
• expr1 || expr2
• expr1 is evaluated.
• expr2 is only evaluated if expr1 was false.
• Examples
• open (…) || die “couldn’t open file”;
• $debug && print “user’s name is $name\n”;
11
Equality Operators for Strings
• Equality/ Inequality : eq and ne
$language = “Perl”;
if ($language == “Perl”) ... # Wrong!
if ($language eq “Perl”) ... #Correct
• Use eq / ne rather than == / != for strings
12
Relational Operators for Strings
• Greater than• Numeric : > String : gt
• Greater than or equal to• Numeric : >= String : ge
• Less than• Numeric : < String : lt
• Less than or equal to• Numeric : <= String : le
13
String Functions
• Convert to upper case• $name = uc($name);
• Convert only the first char to upper case• $name = ucfirst($name);
• Convert to lower case• $name = lc($name);
• Convert only the first char to lower case• $name = lcfirst($name);
14
A String Example Program
• Convert to upper case• $name = uc($name);
• Convert only the first char to upper case• $name = ucfirst($name);
• Convert to lower case• $name = lc($name);
• Convert only the first char to lower case• $name = lcfirst($name);
#!/usr/bin/perl$var1 = “larry”;$var2 = “moe”;$var3 = “shemp”;……Output: Larry, MOE, sHEMP
15
A String Example Program
#!/usr/local/bin/perl
$var1 = “larry”;
$var2 = “moe”;
$var3 = “shemp”;
print ucfirst($var1); # Prints 'Larry'
print uc($var2); # Prints 'MOE'
print lcfirst(uc($var3)); # Prints 'sHEMP'
String Operators
• String Catenation (.) Append two strings together.“Happy” . “ Birthday” → “Happy Birthday.”
$str . “ Holidays” → “Happy Holidays.”
The operands are not effected by (.)
• Repetition operator (x)“Beat OU! ” x 3 → “Beat OU! Beat OU! Beat OU! ”
• What about?“Happy ” . “Birthday! ” x 2
→ “Happy Birthday! Birthday! ”
Chop and Chomp
• Chop removes the last character in a string.chop(“apples”) → “apple”
If $a, $b, and $c are “a”, “an”, and “ant”, then chop($a, $b, $c) →“” “a” “an”
• Chomp removes the ending input record separator(e.g. newline) in a string.• If string does not end with an input record separator, then
chomp does nothing to the string and returns 0.
index and rindex
• index searches for the starting position of asubstring.
• rindex same as index except search is donefrom right to left.
• Examples:• index(“apples”, “pp”) returns 1
• rindex(“apples”, “pp”) returns 1
• index(“apples”, “p”) returns 1
• rindex(“apples”, “p”) returns 2
• index(“apples”, “q”) returns -1
substr
• substr extracts a substring
• The way to call it is:• substr(string, position, length)
• Examples:• substr(“fruit juice”, 0, 3) returns “fru”
• substr(“fruit juice”, 3, 5) returns “it ju”
• substr(“fruit juice”, -3, 3) returns “ice”
join
• Like (.) but appends several strings separated by adeliminator.
• The way to call it is:
join Expression, List
• Example: $month = “09”, $day = “01”, $year = “05”join ‘/’, $month, $day, $year → “09/01/05”.
join ‘/’, $month, $day, 2005 → ??
Assignments
• Simple assignment operators (=)$x = 2;
$average = $sum / $total;
$x = $y = $b = 2;
$result = 17 * ($sum = $x + $y);
chomp($str = $str1. $str1);
• Compound assignment operators (<op>=)$sum += $new_value;
$str .= “ing”;
$result **= 4;
numeric vs. string comparisons
#!/usr/bin/perl
$a = "123";
$b = "1234";
$c = "124";
if ($b > $c) {
print "$b > $c\n";
} else {
print "$b <= $c\n";
}
if ($b gt $c) {
print "$b gt $c\n";
} else {
print "$b le $c\n";
}
1234 > 124
1234 le 124
Quoting special characters
23
\| # Vertical bar
\[ # An open square bracket
\) # A closing parenthesis
\* # An asterisk
\^ # A carat symbol
\/ # A slash
\\ # A backslash
Alternatives and parentheses
24
jelly|cream # Either jelly or cream
(eg|le)gs # Either eggs or legs
(da)+ # Either da or dada or dadada or...
Another Example
25
#!/usr/bin/perl
my @lines = ("Boston is cold.",
"I like the Boston Red Sox.",
"Boston drivers make me see red!" );
foreach my $line (@lines)
{
if ($line =~ /Boston.*red/i )
{
print "$line\n";
}
}
Thankyou
26
Top Related