This document provides a 3-sentence summary of a Perl programming course document on syntax:
The document covers Perl programming syntax including declarations, statements, comments, operators, loops, and conditionals. Sections include declarations of variables and subroutines, simple and compound statements, comments and documentation, conditional statements, loops and loop control, logical and mathematical operators, and operator precedence. The goal of the course is to teach the essential Perl syntax for writing Perl programs.
2. Contents
1. Declarations
2. Simple Statements
3. Compound Statements
4. Comments and POD
5. Conditional Statements
(Statement Modifiers)
6. Loops and loop control
7. Logical operators
8. Mathematical operators
9. Operator Precedence and Associativity
10.Error handling
3. Declarations
• my - declare and assign a local variable
(lexical scoping)
• our - declare and assign a package
variable (lexical scoping)
• local - create a temporary value for a
global variable (dynamic scoping)
• sub - declare a subroutine, possibly
anonymously
4. Declarations
• Example:
use strict; use warnings;
our $dog = 'Puffy';
{
local $ =$/;
print 'A line-feed is appended.';
}
tell_dogs();
print 'No new line at the end. ';
print 'A line feed is appended.'.$/; #;)
sub tell_dogs {
local $ =$/;
print 'Our dog is named ' . $dog;
my $dog = 'Betty';
print 'My dog is named ' . $dog;
}
5. Simple Statements
• The only kind of simple statement is an
expression evaluated for its side effects.
• Every simple statement must be terminated
with a semicolon(;).
• If it is the final statement in a block, the
semicolon is optional.
• eval{} and do{} look like compound
statements, but aren't
• eval{} and do{} need an explicit termination
6. Simple Statements
• Example:
use strict;
use warnings;
$ = $/;
my $simple = 'A simple statement.';
print $simple;
eval { print $simple };
do { print $simple };
do {
$_++;
print $simple ,' ',$_,'+2'
};
7. Compound Statements
• A compound statement usually contains:
• labels
• conditional constructions and blocks
• several simple statements enclosed in
a block
• the block defines a scope
8. Compound Statements
(2)
• A BLOCK is delimited by curly brackets – {}
• The braces are required
• Perl offers several ways to write conditionals
without curly brackets.
• The continue BLOCK is always executed just
before the conditional is about to be evaluated
again.
• A LABEL gives its associated control flow
structure a name.
if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
LABEL while (EXPR) BLOCK
LABEL until (EXPR) BLOCK continue BLOCK
LABEL for (EXPR; EXPR; EXPR) BLOCK
LABEL foreach VAR (LIST) BLOCK continue BLOCK
9. Compound Statements
• Examples:
use strict; use warnings; $ = $/;
use strict; use warnings; $ = $/;
unless( open(FH,$0)){
die 'I do not exist on disk!'. $^E
}
else {
local $ = undef;#slurp mode
my $c=1;
print "$0: ", sprintf('%02d',$c++), " $_" while <FH>;
}
print $/.'---';
my $hashref = {me=>1,you=>2,he=>3};
exists $hashref->{she}
and print 'she: '.$hashref->{she}
or print 'she does not exists.'
and print sort values %$hashref;
10. Compound Statements
(2)
• Examples:
my $c = 0;
while ($c <= 10){
print $c;
}
continue {
$c++;
print $c;
};
########################################
A_LABEL: for my $m (1..10){
ANOTHER: for my $s(0..60) {
last A_LABEL if $m > 4;
last if $s > 4 and print '---';
print sprintf('%1$02d.%2$02d',$m,$s) ;
}
}
11. Comments and POD
• Text from a "#" character until the end of the line is a
comment
Exceptions include "#" inside a string or regular expression.
• POD is a simple-to-use markup language used for writing
documentation for Perl, Perl programs, and Perl modules.
use strict; use warnings; $ = $/;
my $simple = 'A simple statement.#not a comment.';
print $simple;#this is a comment
$simple =~ s#a##ig;
print $simple;
$simple =~ s/#//ig;
print $simple;
=pod
I like to use POD for multi-line comments
but it is much more than that.
=cut
print $0 . ' finished.';
13. Conditional Statements
• Truth and Falsehood
• The number 0, the strings '0' and '', the
empty list (), and undef are all false in a
boolean context
• All other values are true
• Negation of a true value by ! or not returns a
special false value.
When evaluated as a string it is treated as '',
but as a number, it is treated as 0.
14. Conditional Statements
• if/elsif/unless/else
use strict; use warnings; $ = $/;
unless( open(FH,$0) ){
die 'I do not exist on disk!'. $^E
}
else {
local $ = undef; my $c = 1;
print "$0: ", sprintf('%02d',$c++), " $_"
while <FH>;
}
my $hashref = {me=>1,you=>2,he=>3};
if ( exists $hashref->{she} ) {
print 'she:'.$hashref->{she};
}
else {
print 'she does not exists.';
print sort values %$hashref;
}
15. Conditional Statements
• Statement modifiers (suffix notation)
use strict; use warnings; $ = $/;
{
my $c=1;
local $ = undef;
do {
print "$0: ", sprintf('%02d',$c++), " $_"
while <FH>
} if open(FH,$0)
or die 'I do not exist on disk!'. $^E;
}
my $hashref = {me=>1,you=>2,he=>3};
print 'she:'.$hashref->{she}
if ( exists $hashref->{she} );
do {
print 'she does not exists.';
print sort values %$hashref;
} unless exists $hashref->{she};
16. Loops and Loop Control
• Loops
• for
• foreach
• while
• until
• do while/until
17. Loops and Loop Control
• for
• Perl's C-style for loop works like the
corresponding while loop
for ($i = 1; $i < 10; $i++) {
...
}
is (almost) the same as
$i = 1;
while ($i < 10) {
...
} continue {
$i++;
}
18. Loops and Loop Control
• foreach
• Iterates over a normal list value and sets the variable
VAR to be each element of the list in turn
• If preceded with my, it is visible only within the loop
• Otherwise, the variable is implicitly local to the loop
and regains its former value upon exiting the loop
• If VAR is omitted, $_ is set to each value
• You can use foreach for readability or for for
brevity
19. Loops and Loop Control
• foreach – Example:
my @pets = qw|Goldy Amelia Jako|;
my $favorite = 'Puffy';;
foreach $favorite(@pets) {
print 'My favourite pet is:' . $favorite;
}
print 'My favourite pet is:' . $favorite;#Puffy
for $favorite(@pets) {
print 'My favourite pet is:' . $favorite;
}
print 'My favourite pet is:' . $favorite;#Puffy
unshift @pets,$favorite;
for (@pets) {
print 'My favourite pet is:' . $_;
}
#...
20. Loops and Loop Control
• while
repeats a block of code as long as a condition is
true
• do while
executes the do at least once before evaluating
condition in while
$|++;# enable $OUTPUT_AUTOFLUSH
my @sufx = qw(th st nd rd th th th th th th th);
my $i = 1;
while ($i<=10) {
print "This is $i$sufx[$i] iteration";
sleep 1;
$i++;
}
do { print "The $i became $i" } while $i < 10;
print '- ' x $c, $c and $c++ while ($c<=10);
21. Loops and Loop Control
• until
repeats a block of code as long as a condition
is NOT true
• do until
executes the do at least once before evaluating
condition in until
$|++;# enable $OUTPUT_AUTOFLUSH
my @sufx = qw(th st nd rd th th th th th th th);
$i = 10;
until ($i<1) {
print "This is $i$sufx[$i] countdown";
sleep 1;
$i--;
}
do {print "T$i became $i"; $i--} until $i < 1;
22. Loops and Loop Control
• Loop control
• next
• last
• redo
• continue
23. Loops and Loop Control
• Loop control
• next
starts the next iteration of the loop
(continue in C)
• last
immediately exits the loop (break in C)
• redo
restarts the loop block without evaluating
the conditional again
• continue
is always executed just before
the conditional is about to be evaluated again
24. Loops and Loop Control
• Loop control
• next
• If LABEL is omitted, refers to the innermost
enclosing loop
• cannot be used to exit a block which
returns a value such as
eval {}, sub {} or do {}
• should not be used to exit
a grep() or map() operation
25. Loops and Loop Control
(2)
• Loop control
• next
my $c = 1;
while (<DATA>){
next unless /perl/;
chomp and print "$c: $_";
$c++;
}
__DATA__
This section of a perl file
can be used by the perl program
above in the same file to store
and use some textual data
perl rocks!!!
Will the above line print if we remove this one?
26. Loops and Loop Control
• Loop control
• last
• If LABEL is omitted, refers to the innermost
enclosing loop
• cannot be used to exit a block which
returns a value such as
eval {}, sub {} or do {}
• should not be used to exit a grep() or map()
operation
27. Loops and Loop Control
(2)
• Loop control
• last
my $c = 1;
while (<DATA>){
last unless /perl/;
chomp and print "$c: $_";
$c++;
}
__DATA__
This section of a perl file
can be used by the perl program
above in the same file to store
and use some textual data
perl rocks!!!
28. Loops and Loop Control
• Loop control
• redo
• skips the remaining BLOCK
• does not execute any continue block
(even if it exists)
• If the LABEL is omitted, the command refers
to the innermost enclosing loop
• cannot be used to retry a block which returns
a value such as eval {}, sub {} or do {}
• should not be used to exit a grep() or map()
operation
29. Loops and Loop Control
(2)
• Loop control
my ($c, $redone) = (1,0);
• redo while (<DATA>){
chomp; print "$c: $_"; $c++;
if ($_ =~ /perl/ and not $redone) {
$redone++;
redo;
}
elsif($_ =~ /perl/ and $redone) {
$redone--;
next;
}
}
__DATA__
This section of a perl file
can be used by the perl program
above in the same file to store
and use some textual data
perl rocks!!!
30. Loops and Loop Control
• Loop control
• continue
• can be used to increment a loop variable,
even when the loop has been continued via
the next statement
• last, next, or redo may appear within a
continue block
• last, next(!), and redo will behave
as in the main block
31. Loops and Loop Control
• Loop control
• continue
my ($c,$reached_10) = (1,);
while ($c) {
print '- ' x $c, $c;
} continue {
last if ($c == 1 and $reached_10);
$c-- if $reached_10;
$c++ if $c < 10 and not $reached_10;
$reached_10++ if $c == 10;
}
32. Logical Operators
• &&/and
• Binary "and" returns the logical conjunction of
the two surrounding expressions.
• and is equivalent to && except for the very low
precedence
• the right expression is evaluated only if the left
expression is true
my ($me,$you) = qw(me you);
print 'We are here:'.($me && $you) if ($me && $you);
print 'We are here:'.($me and $you) if ($me and $you);
undef $me;
print 'We are here:' if ($me and $you)
or die 'Someone';
33. Logical Operators
• ||/or
• Binary or returns the logical disjunction
of the two surrounding expressions
• or is equivalent to || except for the very
low precedence
• the right expression is evaluated only if
the left expression is false
• use or only for control flow
34. Logical Operators
• ||/or
Example:
my ($me,$you) = qw(me you);
print 'Somebody is here:'.($me || $you)
if ($me || $you);
print 'Somebody is here:'.($me or $you)
if ($me or $you);
($me,$you) = ('me', undef);
print 'Somebody is here:'.($me or $you)
if ($me or $you) or die 'Nooo..';
($me,$you) = (undef, 'you');
print 'Somebody is here:'.($me or $you)
if ($me or $you) or die 'no one';
35. Logical Operators
• !/not
• Unary "not" returns the logical negation
of the expression to its right
• the equivalent of "!" except for the very
low precedence
use Config;
print 'Do my perl uses old threads?';
print 'No' if !$Config{use5005threads};
print 'I do not have extras' if !$Config{extras};
print 'I do not have mail' if not $Config{mail};
36. Logical Operators
• The Ternary Operator, ?:
• ?: is an if-then-else test, all in one
expression
• "ternary" – takes three operands
• if the first expression is true, the second is
evaluated, the third is ignored
• if the first expression is false, the second is
ignored, and the third is evaluated as the
value of the whole
1 < 2 ? print 'true' : print 'false';
37. Mathematical Operators
• Additive Operators
• Binary "+" returns the sum of two
numbers
• Binary "-" returns the difference of two
numbers
• Note: Binary "." concatenates two strings
print 3+2;
print 2-3;
print 2.3; #;)
print '2'.'3';
38. Mathematical Operators
• Multiplicative Operators
• Binary "*" multiplies two numbers
• Binary "/" divides two numbers
• Binary "%" computes the modulus of two
numbers
• Binary "x" is the repetition operator
print 3 * 2;
print 2 / 3;
print "oddn" if 3 % 2; #;)
print 2 x 3;
39. Mathematical Operators
• Exponentiation
• Binary "**" is the exponentiation operator
• binds more tightly than unary minus, so
-2**4 is -(2**4), not (-2)**4
• Auto-increment and Auto-decrement
• "++" and "--" work as in C
print -2**4;#-16
my $a = 2;
print $a++; #2
print ++$a; #4
print $a--; #4
print --$a; #2
40. Operator Precedence
and Associativity
• Operator precedence means some operators are
evaluated before others.
• Operator associativity defines what happens if a
sequence of the same operators is used one after
another: whether the evaluator will evaluate the left
operations first or the right.
• See perlop/Operator Precedence and Associativity
#precedence
2 + 4 * 5 == 2 + 20 == 22 and not 6 * 5 == 30
#associativity
8 - 4 – 2 == 4 - 2 == 2 and not 8 - 2 == 6
41. Operator Precedence
and Associativity
• listed from highest precedence to lowest
• operators borrowed from C keep the same precedence
relationship with each other
left terms and list operators (leftward)
left ->
nonassoc ++ --
right **
right ! ~ and unary + and -
left =~ !~
left * / % x
left + - .
left << >>
nonassoc named unary operators
nonassoc < > <= >= lt gt le ge
nonassoc == != <=> eq ne cmp ~~
...
to be continued
42. Operator Precedence
and Associativity
(2)
• Many operators can be overloaded for objects.
• See the overload manpage
...
continued
left &
left | ^
left &&
left || //
nonassoc .. ...
right ?:
right = += -= *= etc.
left , =>
nonassoc list operators (rightward)
right not
left and
left or xor
43. Error Handling
• die
• warn
• eval{statements()};
do{something()} if($@)
warn 'Default variable is undefined' unless $_;
eval ' a syntax error or any failure';
if($@){
warn 'You spoiled everything';
}
44. Error Handling
• Carp
• carp - warn of errors
(from perspective of caller)
• cluck - warn of errors with stack backtrace
(not exported by default)
• croak - die of errors
(from perspective of caller)
• confess - die of errors with stack backtrace
45. Error Handling
• Carp – Example:
use Carp qw(cluck croak confess);
other_place();
croak "We're outta here!";
sub here {
$ARGV[0] ||= 'try';
if ($ARGV[0] =~ /try/){
cluck "nThis is how we got here!"
}
elsif ($ARGV[0] =~ /die/){
confess "nNothing to live for!";
}
}
sub there { here; }
sub other_place { there }
47. Exercises
1. Write a program that iterates from 3 to 15 and then
from 15 to 3. Print every iteration on the screen.
Try to write it from scratch.
2. Write a program that dies with an error message if
the argument on the command line contains the
word “die”.
3. Write a program that tries to guess the argument
to the script if it contains the numbers 1 or 2 and
prints different messages depending on the
argument. Try not to use if/elsif/unless/else.