Perl programming session 5 operators in perl

26
Session 5 Operators in Perl RAM N SANGWAN WWW.RNSANGWAN.COM 1

Transcript of Perl programming session 5 operators in perl

Page 1: Perl programming session 5 operators in perl

Session 5 Operators in PerlRAM N SANGWAN

WWW.RNSANGWAN.COM

1

Page 2: Perl programming session 5 operators in perl

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

Page 3: Perl programming session 5 operators in perl

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;

Page 4: Perl programming session 5 operators in perl

Operators - Assignments

• As usual: = += -= *= /= **= <<= >>=$value *= 5;

$longword <<= 16;

• Increment: ++$counter++

++$counter

• Decrement: --$num_tries--

--$num_tries

Page 5: Perl programming session 5 operators in perl

Numeric Operators

Operator Associativity

++ -- none

unary - right

** right

* / % left

binary + - left

++ and – have the highest precedence.

Page 6: Perl programming session 5 operators in perl

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

Page 7: Perl programming session 5 operators in perl

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--

Page 8: Perl programming session 5 operators in perl

Operators - Boolean

• Boolean (against bits in each byte)• Usual operators: & |

• Exclusive-or: ^

• Bitwise Negation: ~

$picture = $backgnd & ~$mask | $image;

• Boolean Assignment• &= |= ^=

$picture &= $mask;

Page 9: Perl programming session 5 operators in perl

Operators-Logical (expressions)

• && And operator

• | | Or operator

• ! Not operator

Page 10: Perl programming session 5 operators in perl

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”;

Page 11: Perl programming session 5 operators in perl

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

Page 12: Perl programming session 5 operators in perl

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

Page 13: Perl programming session 5 operators in perl

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);

Page 14: Perl programming session 5 operators in perl

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

Page 15: Perl programming session 5 operators in perl

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'

Page 16: Perl programming session 5 operators in perl

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! ”

Page 17: Perl programming session 5 operators in perl

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.

Page 18: Perl programming session 5 operators in perl

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

Page 19: Perl programming session 5 operators in perl

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”

Page 20: Perl programming session 5 operators in perl

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 → ??

Page 21: Perl programming session 5 operators in perl

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;

Page 22: Perl programming session 5 operators in perl

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

Page 23: Perl programming session 5 operators in perl

Quoting special characters

23

\| # Vertical bar

\[ # An open square bracket

\) # A closing parenthesis

\* # An asterisk

\^ # A carat symbol

\/ # A slash

\\ # A backslash

Page 24: Perl programming session 5 operators in perl

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...

Page 25: Perl programming session 5 operators in perl

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";

}

}

Page 26: Perl programming session 5 operators in perl

Thankyou

26