Python & Perl
Lecture 16
Department of Computer ScienceUtah State University
Outline
● Identifiers and scopes● Arrays
Identifiers & Scopes
Scopes● An identifier's scope is the portion of the program
where the identifier can be referenced● Some identifiers can be referenced from anywhere in
the program● Other identifiers can be referenced from specific
sections of the program● In Perl, an identifier can have three scopes: global,
lexical, and dynamic
Global Scope● The keyword our defines a global variable● If there is no keyword in front of a variable, it becomes
global by default● Global variables exist for the entire execution of the
program and can be manipulated from anywhere in the program
● Examples:our $x = 10;
Lexical Scope● The keyword my defines a lexical identifier● A lexically scoped identifier exists only during the
block in which it is defined● Examples:
my $x = 10;
Dynamic Scope● The keyword local defines a dynamic identifier● Like a lexically scoped identifier, a dynamically scoped
identifier exists in the block in which it is created● In addition, dynamic identifiers are accessible to all
subroutines (Perl term for functions) called from that block in which they (identifiers) are defined
● Examples:local $x = 10;
Strict Variable Scoping● Place “use strict;” at the beginning of your Perl file
to make sure that all identifiers are explicitly scoped● Perl uses packages (Perl's term for namespaces) to
determine the accessibility of identifiers● Note that “use strict;” will cause some code not to
compile
Example: scoping_01.pl#!/usr/bin/perl
use warnings;
$str = 'rock violin'; ## there is no “use strict;”, the compiler is silent
print 'We like ' . $str . "\n";
{ ## entering a new scope
$str = 'classical violin'; ## $str is set to 'classical violin'
print 'We like ' . $str . "\n";
} ## leaving the scope
## global $str is still 'classical violin'
print 'We like ' . $str . "\n";
Example: scoping_01.pl
● The output of scoping_01.pl is as follows:
We like rock violin
We like classical violin
We like classical violin
Example: scoping_02.pl#!/usr/bin/perl
use warnings;
use strict; ## with this in place, the program does not compile.
$str = 'rock violin';
print 'We like ' . $str . "\n";
{ ## entering a new scope
$str = 'classical violin'; ## $str is set to 'classical violin'
print 'We like ' . $str . "\n";
} ## leaving the scope
## global $str is still 'classical violin'
print 'We like ' . $str . "\n";
Example: scoping_02.pl
● The output of scoping_02.pl is as follows:Global symbol "$str" requires explicit package name at ./scoping_02.pl line 9.
Global symbol "$str" requires explicit package name at ./scoping_02.pl line 11.
Global symbol "$str" requires explicit package name at ./scoping_02.pl line 13.
Global symbol "$str" requires explicit package name at ./scoping_02.pl line 15.
Global symbol "$str" requires explicit package name at ./scoping_02.pl line 18.
Execution of ./scoping_02.pl aborted due to compilation errors.
Example: scoping_03.pl#!/usr/bin/perl
use warnings;
use strict;
our $str = 'rock violin'; ## we add our and the program compiles.
print 'We like ' . $str . "\n";
{ ## entering a new scope
$str = 'classical violin'; ## $str is set to 'classical violin'
print 'We like ' . $str . "\n";
} ## leaving the scope
## global $str is still 'classical violin'
print 'We like ' . $str . "\n";
Example: scoping_03.pl
● The output of scoping_03.pl is as follows:
We like rock violin
We like classical violin
We like classical violin
Example: scoping_04.pl#!/usr/bin/perl
use warnings;
use strict;
our $str = 'rock violin'; ## $str is global
print 'We like ' . $str . "\n";
{ ## entering a new scope
my $str = 'classical violin'; ## this $str is lexical
print 'We like ' . $str . "\n";
} ## leaving the scope
## global $str is still 'rock violin'
print 'We like ' . $str . "\n";
Example: scoping_04.pl
● The output of scoping_04.pl is as follows:
We like rock violin
We like classical violin
We like rock violin
Arrays
Arrays● Array variables are prefixed with the @ type identifier
● The most straightforward way to create an array is to define an array variable and to assign to it a list of values
● @a1 = ("file1.txt", "file2.txt", "file3.txt");
● In Perl, the lists are flattened when they are evaluated● @a2 = ("file1.txt", (("file2.txt")), "file3.txt");
● @a1 and @a2 are the same
Creation and Manipulation
● There are four basic ways to create an array in Perl:
Assign a list of values to an array variable Assign a value to a non-existing element
Use the qw operator
Use the range operator
Assigning a List of Values
● @numbers = (1, “one”, 2, “two”, 3, “three”);
● $numbers[0] refers to 1
● $numbers[1] refers to “one”
● $numbers[2] refers to 2
● $numbers[3] refers to “two”
● $numbers[4] refers to 3
● $numbers[5] refers to “three”
array_manip.pl
Example
Assign a Value to a Non-Existing Element
● When a value is assigned to a non-existing element, the array element is automatically created by Perl
● The same concept applies to adding new elements to an array that already exists
● Accessing an array element for which the value has not been provided returns undef
● It is possible to check if an array element is defined using the function defined
Use qw Operator
● The qw operator simplifies the creation of lists of strings with no spaces
● qw takes a list of alphanumeric character sequences separated by spaces and converts them into a list of strings
● Each alphanumeric character sequence is converted into a separate string
array_manip2.pl
Example
Use the range (x .. y) Operator● The range (x .. y) operator works on numeric and
string values ● The operator tries to generate all consecutive values
that start at x and end at y by using the increment operator
● Use of this operator is straightforward with numbers but may be tricky with strings
Numeric Ranges● @numbers = (1 .. 5); ● 1 is incremented to 2; 2 is incremented to 3; 3 is
incremented to 4, etc. ● (1 .. 5) is the same as (1, 2, 3, 4, 5)● These two statements are equivalent:● @numbers = (1 .. 5);● @numbers = (1, 2, 3, 4, 5);
Numeric Ranges● @numbers = (-5 .. -1); ● The range boundaries can be negative so long as we
can get from the left boundary to the right one by increments
● (-5 .. -1) is the same as (-5, -4, -3, -2, -1)
● These two statements are equivalent:● @numbers = (-5 .. -1);● @numbers = (-5, -4, -3, -2, -1);
Numeric Ranges● @numbers = (-1 .. -10); ● If it is impossible to get from the left boundary to the
right boundary, the range is empty● (-1 .. -10) is the same as ()● These two statements are equivalent:● @numbers = (-1 .. -10);● @numbers = ();
Numeric Ranges● @numbers = (1.1 .. 3.1); ● The float boundaries are truncated● (1.1 .. 3.1) is the same as (1 .. 3)● These two statements are equivalent:● @numbers = (1.1 .. 3.1);● @numbers = (1, 2, 3);
String Ranges● @chars = ('F' .. 'I');
● 'F' is incremented to 'G'; 'G' to 'H'; 'H' to 'I'
● ('F' .. 'I') is the same as ('F', 'G', 'H', 'I')
● These two statements are equivalent:● @chars = ('F' .. 'I');● @chars = ('F', 'G', 'H', 'I');
String Ranges● @chars = ('ab' .. 'af'); ● When a string is incremented the last character in the
string is incremented● 'ab' is incremented to 'ac'; 'ac' to 'ad'; 'ad' to 'ae'; 'ae' to 'af'
● ('ab' .. 'af') is the same as ('ab', 'ac', 'ad', 'ae', 'af')
String Ranges● @chars = ('AZ' .. 'BG'); ● When the last character in the string cannot be
incremented, its value is wrapped around and the character to the left of the last one is incremented
● 'AZ' becomes 'BA'; 'BA' becomes 'BB'; 'BB' becomes 'BC', etc.
● ('AZ' .. 'BG') is the same as ('AZ', 'BA', 'BB', 'BC', 'BD', 'BE', 'BG')
Consecutive Array Slicing● If @a is an array, then @a[x .. y], for x <= y, is a consecutive
slice (sub-array) of @a that consists of $a[x], $a[x+1], $a[x+2], …, $a[y]
● If @a is an array, then @a[x .. y], for x > y, is empty● If @a is an array, then x or y in @a[x .. y] can be negative● Consecutive slices can be assigned new values
consec_array_slicing.pl
Example
Non-consecutive Array Slicing● If @a is an array, then @a[index_seq] is a non-consecutive
slice if index_seq is a comma separated sequence of indexes● Examples:
@a[1, 4, 5] @a[5, 1, 4] @a[-1, 3, 2]
● Non-consecutive array slices can be assigned new values
nonconsec_array_slicing.pl
Example
Array Functions push, pop, unshift, shift
Array Functions● push – inserts elements at the end of the array● pop – removes the last element from the array● unshift – inserts an element at the beginning of
the array● shift – removes and returns the element at the
beginning of the array
Example: pop & push● Display the following pattern of numbers
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*
Example: pop & push● Pseudocode:
1. Use push to push '*' one at a time at the end of @asterisks
2. Display @asterisks after every push
3. Pop '*' one at a time from the end of @asterisks
4. Diplay @asterisks after every pop
push_pop.pl
Example
Example: shift & unshift● Display the following pattern of numbers
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
Example: unshift & shift● Pseudocode:
1. Use unshift to insert numbers 1 through 5 one at a time at the front of @numbers
2. Print @numbers after every unshift
3. Use shift to remove elements one at a time from the front of @numbers
4. Print @numbers after every shift
unshift_shift.pl
Source Code
Array Manipulation
Three Cases of Array Assignment
● Case 1: Array has as many values as there are variables
● Case 2: Array has fewer values than there are variables
● Case 3: Array has more values than there are variables
Example
array_assignment.pl
Computing Array Length● Perl's function length returns the number of
characters in its string argument● So it can be used to compute the length of strings in
characters● This function cannot be used compute the length of
an array, because it returns the number of characters in the integer that denotes the length of the array argument
Computing Array Length● If @data is an array, $#data refers to its last index● If @data is (1, 2, 3), then $#data == 2
● If @data is an array, the length of @data is $#data + 1
● Another way to compute the length of @data is scalar @data
Example
array_length.pl
Iterating Through Arrays● You can use while loops to iterate through arrays● You can also use for and foreach loops to iterate
through arrays● If there is no control variable used, the array values
are assigned to $_
Examples
array_foreach.plforeach_expression.pl
Loop Control Statements
● Loop control statements change execution from its normal sequence.
● When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
next statement
● Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating
$a = 10;while( $a < 20 ){ if( $a == 15) { # skip the iteration. $a = $a + 1; next; } print "value of a: $a\n"; $a = $a + 1;}
value of a: 10value of a: 11value of a: 12value of a: 13value of a: 14value of a: 16value of a: 17value of a: 18value of a: 19
last statement
● Terminates the loop statement and transfers execution to the statement immediately following the loop.
$a = 10;while( $a < 20 ){ if( $a == 15) { # terminate the loop. $a = $a + 1; last; } print "value of a: $a\n"; $a = $a + 1;}
value of a: 10value of a: 11value of a: 12value of a: 13value of a: 14
EXIT & DIE
EXIT● As its name suggests, exit() exits a Perl program and
returns the value back to the calling program or the OS● The value of 0 means that the program terminated normally● A non-zero value, typically 1, signals an abnormal
termination● If no argument is provided, 0 is returned
DIE● The function die() is used for serious errors● die() takes a string and prints it to the standard error
output● die() calls exit() with a non-zero value● die() is a great debugging tool: it prints out the line
number of the program where it was executed
Reading & References● http://perldoc.perl.org/● James Lee. Beginning Perl, 2nd Edition, APRESS● Dietel, Dietel, Nieto, McPhie. Perl How to Program,
Prentice Hall