syntax

47
Perl Programming Perl Programming Course Course Krassimir Berov Syntax Syntax I-can.eu

Upload: krasimir-berov

Post on 09-Jun-2015

426 views

Category:

Technology


0 download

DESCRIPTION

This is the fifth set of slightly updated slides from a Perl programming course that I held some years ago. I want to share it with everyone looking for intransitive Perl-knowledge. A table of content for all presentations can be found at i-can.eu. The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse

TRANSCRIPT

Page 1: Syntax

Perl Programming Perl Programming CourseCourse

Krassimir Berov

SyntaxSyntax

I-can.eu

Page 2: Syntax

ContentsContents

1.1. DeclarationsDeclarations2.2. Simple StatementsSimple Statements3.3. Compound StatementsCompound Statements4.4. Comments and PODComments and POD5.5. Conditional Statements Conditional Statements

(Statement Modifiers)(Statement Modifiers)6.6. Loops and loop controlLoops and loop control7.7. Logical operatorsLogical operators8.8. Mathematical operatorsMathematical operators9.9. Operator Precedence and AssociativityOperator Precedence and Associativity10.10.Error handlingError handling

Page 3: Syntax

DeclarationsDeclarations

• my - declare and assign a local variable my - declare and assign a local variable (lexical scoping)(lexical scoping)

• our - declare and assign a package our - declare and assign a package variable (lexical scoping)variable (lexical scoping)

• local - create a temporary value for a local - create a temporary value for a global variable (dynamic scoping)global variable (dynamic scoping)

• sub - declare a subroutine, possibly sub - declare a subroutine, possibly anonymouslyanonymously

Page 4: Syntax

DeclarationsDeclarations

• Example:Example:

use strict; use warnings;use strict; use warnings;our $dog = 'Puffy';our $dog = 'Puffy';{{ local $\ =$/;local $\ =$/; print 'A line-feed is appended.';print 'A line-feed is appended.';}}tell_dogs();tell_dogs();print 'No new line at the end. ';print 'No new line at the end. ';print 'A line feed is appended.'.$/; #;)print 'A line feed is appended.'.$/; #;)

sub tell_dogs {sub tell_dogs { local $\ =$/;local $\ =$/; print 'Our dog is named ' . $dog;print 'Our dog is named ' . $dog; my $dog = 'Betty';my $dog = 'Betty'; print 'My dog is named ' . $dog;print 'My dog is named ' . $dog;}}

Page 5: Syntax

Simple StatementsSimple Statements

• The only kind of simple statement is an The only kind of simple statement is an expression evaluated for its side effects. expression evaluated for its side effects.

• Every simple statement must be terminated Every simple statement must be terminated with a semicolon(;).with a semicolon(;).

• If it is the final statement in a block, the If it is the final statement in a block, the semicolon is optional.semicolon is optional.

• eval{}eval{} and and do{}do{} look like compound look like compound statements, but aren'tstatements, but aren't

• eval{}eval{} and and do{}do{} need an explicit termination need an explicit termination

Page 6: Syntax

Simple StatementsSimple Statements

• Example:Example:

use strict; use strict; use warnings; use warnings; $\ = $/;$\ = $/;my $simple = 'A simple statement.';my $simple = 'A simple statement.';print $simple;print $simple;eval { print $simple };eval { print $simple };do { print $simple };do { print $simple };do { do { $_++;$_++; print $simple ,' ',$_,'+2'print $simple ,' ',$_,'+2'};};

Page 7: Syntax

Compound StatementsCompound Statements

• A compound statement usually contains: A compound statement usually contains:

• labels labels

• conditional constructions and blocksconditional constructions and blocks

• several simple statements enclosed in several simple statements enclosed in a blocka block

• the block defines a scopethe block defines a scope

Page 8: Syntax

Compound StatementsCompound Statements

• A BLOCK is delimited by curly brackets – {}A BLOCK is delimited by curly brackets – {}

• The braces are requiredThe braces are required

• Perl offers several ways to write conditionals Perl offers several ways to write conditionals without curly brackets.without curly brackets.

• The continue BLOCK is always executed just The continue BLOCK is always executed just before the conditional is about to be evaluated before the conditional is about to be evaluated again. again.

• A LABEL gives its associated control flow A LABEL gives its associated control flow structure a name.structure a name.if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCKif (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCKLABEL while (EXPR) BLOCKLABEL while (EXPR) BLOCKLABEL until (EXPR) BLOCK continue BLOCKLABEL until (EXPR) BLOCK continue BLOCKLABEL for (EXPR; EXPR; EXPR) BLOCKLABEL for (EXPR; EXPR; EXPR) BLOCKLABEL foreach VAR (LIST) BLOCK continue BLOCKLABEL foreach VAR (LIST) BLOCK continue BLOCK

(2)

Page 9: Syntax

Compound StatementsCompound Statements

• Examples:Examples:

use strict; use warnings; $\ = $/;use strict; use warnings; $\ = $/;use strict; use warnings; $\ = $/;use strict; use warnings; $\ = $/;

unless( open(FH,$0)){ unless( open(FH,$0)){ die 'I do not exist on disk!'. $^E die 'I do not exist on disk!'. $^E }}else {else { local $\ = undef;#slurp modelocal $\ = undef;#slurp mode my $c=1;my $c=1; print "$0: ", sprintf('%02d',$c++), " $_" while <FH>;print "$0: ", sprintf('%02d',$c++), " $_" while <FH>;}}print $/.'---'; print $/.'---'; my $hashref = {me=>1,you=>2,he=>3};my $hashref = {me=>1,you=>2,he=>3};exists $hashref->{she}exists $hashref->{she} and print 'she: '.$hashref->{she}and print 'she: '.$hashref->{she} or print 'she does not exists.'or print 'she does not exists.' and print sort values %$hashref;and print sort values %$hashref;

Page 10: Syntax

Compound StatementsCompound Statements

• Examples:Examples:my $c = 0;my $c = 0;while ($c <= 10){while ($c <= 10){ print $c;print $c;} } continue {continue { $c++;$c++; print $c;print $c;};};################################################################################A_LABEL: for my $m (1..10){A_LABEL: for my $m (1..10){ ANOTHER: for my $s(0..60) {ANOTHER: for my $s(0..60) { last A_LABEL if $m > 4;last A_LABEL if $m > 4; last if $s > 4 and print '---';last if $s > 4 and print '---'; print sprintf('%1$02d.%2$02d',$m,$s) ;print sprintf('%1$02d.%2$02d',$m,$s) ; }}} }

(2)

Page 11: Syntax

Comments and PODComments and POD

• Text from a "#" character until the end of the line is a Text from a "#" character until the end of the line is a comment comment Exceptions include "#" inside a string or regular expression.Exceptions include "#" inside a string or regular expression.

• POD is a simple-to-use markup language used for writing POD is a simple-to-use markup language used for writing documentation for Perl, Perl programs, and Perl modules.documentation for Perl, Perl programs, and Perl modules.

use strict; use warnings; $\ = $/;use strict; use warnings; $\ = $/;my $simple = 'A simple statement.#not a comment.';my $simple = 'A simple statement.#not a comment.';print $simple;#this is a commentprint $simple;#this is a comment$simple =~ s#a##ig;$simple =~ s#a##ig;print $simple;print $simple;$simple =~ s/#//ig;$simple =~ s/#//ig;print $simple;print $simple;=pod=podI like to use POD for multi-line commentsI like to use POD for multi-line commentsbut it is much more than that.but it is much more than that.=cut=cutprint $0 . ' finished.';print $0 . ' finished.';

Page 12: Syntax

Conditional StatementsConditional Statements

• Truth and FalsehoodTruth and Falsehood

• if/elsif/unless/elseif/elsif/unless/else

• Statement modifiers (suffix notation)Statement modifiers (suffix notation)

Page 13: Syntax

Conditional StatementsConditional Statements

• Truth and FalsehoodTruth and Falsehood

• The number The number 00, the strings , the strings '0''0' and and '''', the , the empty list empty list ()(), and , and undefundef are all false in a are all false in a boolean contextboolean context

• All other values are trueAll other values are true

• Negation of a true value by Negation of a true value by !! or or notnot returns a returns a special false value. special false value. When evaluated as a string it is treated as '', When evaluated as a string it is treated as '', but as a number, it is treated as 0.but as a number, it is treated as 0.

Page 14: Syntax

Conditional StatementsConditional Statements

• if/elsif/unless/elseif/elsif/unless/elseuse strict; use warnings; $\ = $/;use strict; use warnings; $\ = $/;unless( open(FH,$0) ){unless( open(FH,$0) ){ die 'I do not exist on disk!'. $^Edie 'I do not exist on disk!'. $^E} } else {else { local $\ = undef; my $c = 1;local $\ = undef; my $c = 1; print "$0: ", sprintf('%02d',$c++), " $_" print "$0: ", sprintf('%02d',$c++), " $_" while <FH>;while <FH>;}}my $hashref = {me=>1,you=>2,he=>3};my $hashref = {me=>1,you=>2,he=>3};if ( exists $hashref->{she} ) {if ( exists $hashref->{she} ) { print 'she:'.$hashref->{she};print 'she:'.$hashref->{she};} } else {else { print 'she does not exists.';print 'she does not exists.'; print sort values %$hashref;print sort values %$hashref;}}

Page 15: Syntax

Conditional StatementsConditional Statements

• Statement modifiers (suffix notation)Statement modifiers (suffix notation)use strict; use warnings; $\ = $/;use strict; use warnings; $\ = $/;{{ my $c=1;my $c=1; local $\ = undef;local $\ = undef; do {do { print "$0: ", sprintf('%02d',$c++), " $_"print "$0: ", sprintf('%02d',$c++), " $_" while <FH>while <FH> } if open(FH,$0) } if open(FH,$0) or die 'I do not exist on disk!'. $^E;or die 'I do not exist on disk!'. $^E;}}my $hashref = {me=>1,you=>2,he=>3};my $hashref = {me=>1,you=>2,he=>3};print 'she:'.$hashref->{she} print 'she:'.$hashref->{she} if ( exists $hashref->{she} );if ( exists $hashref->{she} );do {do { print 'she does not exists.';print 'she does not exists.'; print sort values %$hashref;print sort values %$hashref;} unless exists $hashref->{she};} unless exists $hashref->{she};

Page 16: Syntax

Loops and Loop ControlLoops and Loop Control

• LoopsLoops

• forfor

• foreachforeach

• whilewhile

• untiluntil

• do while/untildo while/until

Page 17: Syntax

Loops and Loop ControlLoops and Loop Control

• forfor

• Perl's C-style for loop works like the Perl's C-style for loop works like the corresponding while loopcorresponding while loop

is (almost) the same asis (almost) the same as

for ($i = 1; $i < 10; $i++) {for ($i = 1; $i < 10; $i++) { ......}}

$i = 1;$i = 1;while ($i < 10) {while ($i < 10) { ......} continue {} continue { $i++;$i++;}}

Page 18: Syntax

Loops and Loop ControlLoops and Loop Control

• foreachforeach• Iterates over a normal list value and sets the variable Iterates over a normal list value and sets the variable

VAR to be each element of the list in turnVAR to be each element of the list in turn

• If preceded with If preceded with mymy, it is visible only within the loop, it is visible only within the loop

• Otherwise, the variable is implicitly local to the loop Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loopand regains its former value upon exiting the loop

• If VAR is omitted, If VAR is omitted, $_$_ is set to each value is set to each value

• You can use You can use foreachforeach for readability or for readability or forfor for for brevitybrevity

Page 19: Syntax

Loops and Loop ControlLoops and Loop Control

• foreach – Example:foreach – Example:

my @pets = qw|Goldy Amelia Jako|;my @pets = qw|Goldy Amelia Jako|;my $favorite = 'Puffy';;my $favorite = 'Puffy';;foreach $favorite(@pets) {foreach $favorite(@pets) { print 'My favourite pet is:' . $favorite;print 'My favourite pet is:' . $favorite;}}print 'My favourite pet is:' . $favorite;#Puffyprint 'My favourite pet is:' . $favorite;#Puffyfor $favorite(@pets) {for $favorite(@pets) { print 'My favourite pet is:' . $favorite;print 'My favourite pet is:' . $favorite;}}print 'My favourite pet is:' . $favorite;#Puffyprint 'My favourite pet is:' . $favorite;#Puffyunshift @pets,$favorite;unshift @pets,$favorite;for (@pets) {for (@pets) { print 'My favourite pet is:' . $_;print 'My favourite pet is:' . $_;}}#...#...

Page 20: Syntax

Loops and Loop ControlLoops and Loop Control

• whilewhilerepeats a block of code as long as a condition is repeats a block of code as long as a condition is truetrue

• do whiledo whileexecutes the executes the dodo at least once before evaluating at least once before evaluating condition in condition in whilewhile$|++;# enable $OUTPUT_AUTOFLUSH$|++;# enable $OUTPUT_AUTOFLUSHmy @sufx = qw(th st nd rd th th th th th th th);my @sufx = qw(th st nd rd th th th th th th th);my $i = 1;my $i = 1;while ($i<=10) {while ($i<=10) { print "This is $i$sufx[$i] iteration";print "This is $i$sufx[$i] iteration"; sleep 1;sleep 1; $i++;$i++;}}do { print "The \$i became $i" } while $i < 10;do { print "The \$i became $i" } while $i < 10;print '- ' x $c, $c and $c++ while ($c<=10);print '- ' x $c, $c and $c++ while ($c<=10);

Page 21: Syntax

Loops and Loop ControlLoops and Loop Control

• untiluntilrepeats a block of code as long as a condition repeats a block of code as long as a condition is NOT trueis NOT true

• do untildo untilexecutes the executes the dodo at least once before evaluating at least once before evaluating condition in condition in untiluntil$|++;# enable $OUTPUT_AUTOFLUSH$|++;# enable $OUTPUT_AUTOFLUSHmy @sufx = qw(th st nd rd th th th th th th th);my @sufx = qw(th st nd rd th th th th th th th);$i = 10;$i = 10;until ($i<1) {until ($i<1) { print "This is $i$sufx[$i] countdown";print "This is $i$sufx[$i] countdown"; sleep 1;sleep 1; $i--;$i--;}}do {print "T\$i became $i"; $i--} until $i < 1;do {print "T\$i became $i"; $i--} until $i < 1;

Page 22: Syntax

Loops and Loop ControlLoops and Loop Control

• Loop controlLoop control

• nextnext

• lastlast

• redoredo

• continuecontinue

Page 23: Syntax

Loops and Loop ControlLoops and Loop Control

• Loop controlLoop control

• nextnextstarts the next iteration of the loop starts the next iteration of the loop (continue in C)(continue in C)

• lastlastimmediately exits the loop (break in C)immediately exits the loop (break in C)

• redoredorestarts the loop block without evaluating restarts the loop block without evaluating the conditional againthe conditional again

• continuecontinueis always executed just before is always executed just before the conditional is about to be evaluated againthe conditional is about to be evaluated again

Page 24: Syntax

Loops and Loop ControlLoops and Loop Control

• Loop controlLoop control

• nextnext

• If LABEL is omitted, refers to the innermost If LABEL is omitted, refers to the innermost enclosing loopenclosing loop

• cannot be used to exit a block which cannot be used to exit a block which returns a value such as returns a value such as eval {}, sub {} or do {}eval {}, sub {} or do {}

• should not be used to exit should not be used to exit a grep() or map() operationa grep() or map() operation

Page 25: Syntax

Loops and Loop ControlLoops and Loop Control

• Loop controlLoop control

• nextnext

my $c = 1;my $c = 1;while (<DATA>){while (<DATA>){ next unless /perl/;next unless /perl/; chomp and print "$c: $_";chomp and print "$c: $_"; $c++;$c++;}}__DATA____DATA__This section of a perl fileThis section of a perl filecan be used by the perl programcan be used by the perl programabove in the same file to store above in the same file to store and use some textual dataand use some textual dataperl rocks!!!perl rocks!!!Will the above line print if we remove this one?Will the above line print if we remove this one?

(2)

Page 26: Syntax

Loops and Loop ControlLoops and Loop Control

• Loop controlLoop control

• lastlast

• If LABEL is omitted, refers to the innermost If LABEL is omitted, refers to the innermost enclosing loopenclosing loop

• cannot be used to exit a block which cannot be used to exit a block which returns a value such as returns a value such as eval {}, sub {} or do {}eval {}, sub {} or do {}

• should not be used to exit a grep() or map() should not be used to exit a grep() or map() operationoperation

Page 27: Syntax

Loops and Loop ControlLoops and Loop Control

• Loop controlLoop control

• lastlast

my $c = 1;my $c = 1;while (<DATA>){while (<DATA>){ last unless /perl/;last unless /perl/; chomp and print "$c: $_";chomp and print "$c: $_"; $c++;$c++;}}__DATA____DATA__This section of a perl fileThis section of a perl filecan be used by the perl programcan be used by the perl programabove in the same file to store above in the same file to store and use some textual dataand use some textual dataperl rocks!!!perl rocks!!!

(2)

Page 28: Syntax

Loops and Loop ControlLoops and Loop Control

• Loop controlLoop control

• redoredo

• skips the remaining BLOCKskips the remaining BLOCK

• does not execute any continue block does not execute any continue block (even if it exists)(even if it exists)

• If the LABEL is omitted, the command refers If the LABEL is omitted, the command refers to the innermost enclosing loopto the innermost enclosing loop

• cannot be used to retry a block which returns cannot be used to retry a block which returns a value such as eval {}, sub {} or do {}a value such as eval {}, sub {} or do {}

• should not be used to exit a grep() or map() should not be used to exit a grep() or map() operationoperation

Page 29: Syntax

Loops and Loop ControlLoops and Loop Control

• Loop controlLoop control

• redoredomy ($c, $redone) = (1,0);my ($c, $redone) = (1,0);while (<DATA>){while (<DATA>){ chomp; print "$c: $_"; $c++;chomp; print "$c: $_"; $c++; if ($_ =~ /perl/ and not $redone) {if ($_ =~ /perl/ and not $redone) { $redone++;$redone++; redo;redo; }} elsif($_ =~ /perl/ and $redone) {elsif($_ =~ /perl/ and $redone) { $redone--;$redone--; next;next; }}}}__DATA____DATA__This section of a perl fileThis section of a perl filecan be used by the perl programcan be used by the perl programabove in the same file to store above in the same file to store and use some textual dataand use some textual dataperl rocks!!!perl rocks!!!

(2)

Page 30: Syntax

Loops and Loop ControlLoops and Loop Control

• Loop controlLoop control

• continuecontinue

• can be used to increment a loop variable, can be used to increment a loop variable, even when the loop has been continued via even when the loop has been continued via the the nextnext statement statement

• lastlast, , nextnext, or , or redoredo may appear within a may appear within a continuecontinue block block

• last, next(!)last, next(!), and , and redoredo will behave will behave as in the main blockas in the main block

Page 31: Syntax

Loops and Loop ControlLoops and Loop Control

• Loop controlLoop control

• continuecontinue

my ($c,$reached_10) = (1,);my ($c,$reached_10) = (1,);while ($c) {while ($c) { print '- ' x $c, $c;print '- ' x $c, $c;} continue {} continue { last if ($c == 1 and $reached_10);last if ($c == 1 and $reached_10); $c-- if $reached_10;$c-- if $reached_10; $c++ if $c < 10 and not $reached_10;$c++ if $c < 10 and not $reached_10; $reached_10++ if $c == 10;$reached_10++ if $c == 10;}}

Page 32: Syntax

Logical OperatorsLogical Operators

• &&/and&&/and

• Binary Binary "and" returns the logical conjunction of "and" returns the logical conjunction of the two surrounding expressions.the two surrounding expressions.

• andand is equivalent to && except for the very low is equivalent to && except for the very low precedenceprecedence

• the right expression is evaluated only if the left the right expression is evaluated only if the left expression is trueexpression is true

my ($me,$you) = qw(me you);my ($me,$you) = qw(me you);print 'We are here:'.($me && $you) if ($me && $you);print 'We are here:'.($me && $you) if ($me && $you);print 'We are here:'.($me and $you) if ($me and $you);print 'We are here:'.($me and $you) if ($me and $you);undef $me; undef $me; print 'We are here:' if ($me and $you) print 'We are here:' if ($me and $you) or die 'Someone';or die 'Someone';

Page 33: Syntax

Logical OperatorsLogical Operators

• ||/or||/or

• Binary Binary oror returns the logical disjunction returns the logical disjunction of the two surrounding expressionsof the two surrounding expressions

• oror is equivalent to || except for the very is equivalent to || except for the very low precedencelow precedence

• the right expression is evaluated only if the right expression is evaluated only if the left expression is falsethe left expression is false

• use use oror only for control flow only for control flow

Page 34: Syntax

Logical OperatorsLogical Operators

• ||/or||/orExample:Example:

my ($me,$you) = qw(me you);my ($me,$you) = qw(me you);print 'Somebody is here:'.($me || $you) print 'Somebody is here:'.($me || $you) if ($me || $you);if ($me || $you);print 'Somebody is here:'.($me or $you) print 'Somebody is here:'.($me or $you) if ($me or $you);if ($me or $you);

($me,$you) = ('me', undef);($me,$you) = ('me', undef);print 'Somebody is here:'.($me or $you)print 'Somebody is here:'.($me or $you) if ($me or $you) or die 'Nooo..';if ($me or $you) or die 'Nooo..';

($me,$you) = (undef, 'you');($me,$you) = (undef, 'you');print 'Somebody is here:'.($me or $you)print 'Somebody is here:'.($me or $you) if ($me or $you) or die 'no one';if ($me or $you) or die 'no one';

Page 35: Syntax

Logical OperatorsLogical Operators

• !/not!/not

• Unary "not" returns the logical negation Unary "not" returns the logical negation of the expression to its rightof the expression to its right

• the equivalent of "!" except for the very the equivalent of "!" except for the very low precedencelow precedence

use Config;use Config;print 'Do my perl uses old threads?';print 'Do my perl uses old threads?';print 'No' if !$Config{use5005threads};print 'No' if !$Config{use5005threads};print 'I do not have extras' if !$Config{extras};print 'I do not have extras' if !$Config{extras};print 'I do not have mail' if not $Config{mail};print 'I do not have mail' if not $Config{mail};

Page 36: Syntax

Logical OperatorsLogical Operators

• The Ternary Operator, The Ternary Operator, ?:?:

• ?:?: is an if-then-else test, all in one is an if-then-else test, all in one expressionexpression

• "ternary" – takes three operands"ternary" – takes three operands

• if the first expression is true, the second is if the first expression is true, the second is evaluated, the third is ignoredevaluated, the third is ignored

• if the first expression is false, the second is if the first expression is false, the second is ignored, and the third is evaluated as the ignored, and the third is evaluated as the value of the wholevalue of the whole

1 < 2 ? print 'true' : print 'false';1 < 2 ? print 'true' : print 'false';

Page 37: Syntax

Mathematical OperatorsMathematical Operators

• Additive OperatorsAdditive Operators

• Binary "+" returns the sum of two Binary "+" returns the sum of two numbersnumbers

• Binary "-" returns the difference of two Binary "-" returns the difference of two numbersnumbers

• Note: Binary "." concatenates two stringsNote: Binary "." concatenates two strings

print 3+2;print 3+2;print 2-3;print 2-3;print 2.3; #;)print 2.3; #;)print '2'.'3';print '2'.'3';

Page 38: Syntax

Mathematical OperatorsMathematical Operators

• Multiplicative OperatorsMultiplicative Operators

• Binary "*" multiplies two numbersBinary "*" multiplies two numbers

• Binary "/" divides two numbersBinary "/" divides two numbers

• Binary "%" computes the modulus of two Binary "%" computes the modulus of two numbersnumbers

• Binary "x" is the repetition operatorBinary "x" is the repetition operatorprint 3 * 2;print 3 * 2;print 2 / 3;print 2 / 3;print "odd\n" if 3 % 2; #;)print "odd\n" if 3 % 2; #;)print 2 x 3;print 2 x 3;

Page 39: Syntax

Mathematical OperatorsMathematical Operators

• ExponentiationExponentiation

• Binary "**" is the exponentiation operatorBinary "**" is the exponentiation operator

• binds more tightly than unary minus, so binds more tightly than unary minus, so -2**4 is -(2**4), not (-2)**4-2**4 is -(2**4), not (-2)**4

• Auto-increment and Auto-decrementAuto-increment and Auto-decrement

• "++" and "--" work as in C"++" and "--" work as in C

print -2**4;#-16print -2**4;#-16my $a = 2;my $a = 2;print $a++; #2print $a++; #2print ++$a; #4print ++$a; #4print $a--; #4print $a--; #4print --$a; #2print --$a; #2

Page 40: Syntax

Operator Precedence Operator Precedence and Associativityand Associativity

• Operator precedence means some operators are Operator precedence means some operators are evaluated before others.evaluated before others.

• Operator associativity defines what happens if a Operator associativity defines what happens if a sequence of the same operators is used one after sequence of the same operators is used one after another: whether the evaluator will evaluate the left another: whether the evaluator will evaluate the left operations first or the right.operations first or the right.

• See perlop/Operator Precedence and AssociativitySee perlop/Operator Precedence and Associativity

#precedence#precedence2 + 4 * 5 == 2 + 20 == 22 and not 6 * 5 == 302 + 4 * 5 == 2 + 20 == 22 and not 6 * 5 == 30

#associativity#associativity8 - 4 – 2 == 4 - 2 == 2 and not 8 - 2 == 68 - 4 – 2 == 4 - 2 == 2 and not 8 - 2 == 6

Page 41: Syntax

Operator Precedence Operator Precedence and Associativityand Associativity

• listed from highest precedence to lowestlisted from highest precedence to lowest

• operators borrowed from C keep the same precedence operators borrowed from C keep the same precedence relationship with each otherrelationship with each other left terms and list operators (leftward)left terms and list operators (leftward) left ->left -> nonassoc ++ --nonassoc ++ -- right **right ** right ! ~ \ and unary + and -right ! ~ \ and unary + and - left =~ !~left =~ !~ left * / % xleft * / % x left + - .left + - . left << >>left << >> nonassoc named unary operatorsnonassoc named unary operators nonassoc < > <= >= lt gt le genonassoc < > <= >= lt gt le ge nonassoc == != <=> eq ne cmp ~~nonassoc == != <=> eq ne cmp ~~......to be continuedto be continued

Page 42: Syntax

Operator Precedence Operator Precedence and Associativityand Associativity

• Many operators can be overloaded for objects. Many operators can be overloaded for objects.

• See the overload manpageSee the overload manpage

......continuedcontinued left &left & left | ^left | ^ left &&left && left || //left || // nonassoc .. ...nonassoc .. ... right ?:right ?: right = += -= *= etc.right = += -= *= etc. left , =>left , => nonassoc list operators (rightward)nonassoc list operators (rightward) right notright not left andleft and left or xorleft or xor

(2)

Page 43: Syntax

Error HandlingError Handling

• diedie

• warnwarn

• eval{statements()};eval{statements()};do{something()} if($@)do{something()} if($@)

warn 'Default variable is undefined' unless $_;warn 'Default variable is undefined' unless $_;

eval ' a syntax error or any failure';eval ' a syntax error or any failure';

if($@){if($@){warn 'You spoiled everything';warn 'You spoiled everything';

}}

Page 44: Syntax

Error HandlingError Handling

• CarpCarp

• carp - warn of errors carp - warn of errors (from perspective of caller)(from perspective of caller)

• cluck - warn of errors with stack backtrace cluck - warn of errors with stack backtrace (not exported by default)(not exported by default)

• croak - die of errors croak - die of errors (from perspective of caller)(from perspective of caller)

• confess - die of errors with stack backtraceconfess - die of errors with stack backtrace

Page 45: Syntax

Error HandlingError Handling

• Carp – Example:Carp – Example:use Carp qw(cluck croak confess);use Carp qw(cluck croak confess);other_place();other_place();

croak "We're outta here!";croak "We're outta here!";

sub here { sub here { $ARGV[0] ||= 'try';$ARGV[0] ||= 'try'; if ($ARGV[0] =~ /try/){if ($ARGV[0] =~ /try/){ cluck "\nThis is how we got here!"cluck "\nThis is how we got here!" } } elsif ($ARGV[0] =~ /die/){elsif ($ARGV[0] =~ /die/){ confess "\nNothing to live for!";confess "\nNothing to live for!"; } } }}sub there { here; }sub there { here; }sub other_place { there }sub other_place { there }

Page 46: Syntax

SyntaxSyntax

Questions?Questions?

Page 47: Syntax

ExercisesExercises

1.1. Write a program that iterates from 3 to 15 and then Write a program that iterates from 3 to 15 and then from 15 to 3. Print every iteration on the screen. from 15 to 3. Print every iteration on the screen. Try to write it from scratch.Try to write it from scratch.

2.2. Write a program that dies with an error message if Write a program that dies with an error message if the argument on the command line contains the the argument on the command line contains the word “die”.word “die”.

3.3. Write a program that tries to guess the argument Write a program that tries to guess the argument to the script if it contains the numbers 1 or 2 and to the script if it contains the numbers 1 or 2 and prints different messages depending on the prints different messages depending on the argument. Try not to use if/elsif/unless/else.argument. Try not to use if/elsif/unless/else.