SlideShare ist ein Scribd-Unternehmen logo
1 von 59
Downloaden Sie, um offline zu lesen
Python & Perl
Lecture 16
Department of Computer Science
Utah 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.pl
foreach_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: $an";
$a = $a + 1;
}
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value 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: $an";
$a = $a + 1;
}
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value 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

Weitere ähnliche Inhalte

Was ist angesagt?

16 Java Regex
16 Java Regex16 Java Regex
16 Java Regexwayn
 
Introduction of bison
Introduction of bisonIntroduction of bison
Introduction of bisonvip_du
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionEelco Visser
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in JavaOblivionWalker
 
Applicative Functor - Part 3
Applicative Functor - Part 3Applicative Functor - Part 3
Applicative Functor - Part 3Philip Schwarz
 
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...Philip Schwarz
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Philip Schwarz
 
Operator precedance parsing
Operator precedance parsingOperator precedance parsing
Operator precedance parsingsanchi29
 
Regular Expression
Regular ExpressionRegular Expression
Regular ExpressionLambert Lum
 
Regex Presentation
Regex PresentationRegex Presentation
Regex Presentationarnolambert
 
Regular Expressions grep and egrep
Regular Expressions grep and egrepRegular Expressions grep and egrep
Regular Expressions grep and egrepTri Truong
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
 

Was ist angesagt? (20)

Awk programming
Awk programming Awk programming
Awk programming
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
16 Java Regex
16 Java Regex16 Java Regex
16 Java Regex
 
Introduction of bison
Introduction of bisonIntroduction of bison
Introduction of bison
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint Resolution
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in Java
 
Applicative Functor - Part 3
Applicative Functor - Part 3Applicative Functor - Part 3
Applicative Functor - Part 3
 
Syntaxdirected
SyntaxdirectedSyntaxdirected
Syntaxdirected
 
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
 
State Monad
State MonadState Monad
State Monad
 
Operator precedance parsing
Operator precedance parsingOperator precedance parsing
Operator precedance parsing
 
Perl6 signatures
Perl6 signaturesPerl6 signatures
Perl6 signatures
 
Antlr V3
Antlr V3Antlr V3
Antlr V3
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
Regular Expression
Regular ExpressionRegular Expression
Regular Expression
 
Regex Presentation
Regex PresentationRegex Presentation
Regex Presentation
 
Grep Introduction
Grep IntroductionGrep Introduction
Grep Introduction
 
Regular Expressions grep and egrep
Regular Expressions grep and egrepRegular Expressions grep and egrep
Regular Expressions grep and egrep
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 

Andere mochten auch

Automated posting on facebook and twitter for IIMnet members
Automated posting on facebook and twitter for IIMnet membersAutomated posting on facebook and twitter for IIMnet members
Automated posting on facebook and twitter for IIMnet membersIIMnet Ventures
 
The New Data Security Risk
The New Data Security RiskThe New Data Security Risk
The New Data Security RiskSteve Kirwan
 
Exercicisdetransmissidemovimentambpolitges
Exercicisdetransmissidemovimentambpolitges Exercicisdetransmissidemovimentambpolitges
Exercicisdetransmissidemovimentambpolitges topillo1
 
UB0203 Developing the skills of Academic Numeracy & IT
UB0203 Developing the skills of Academic Numeracy & IT UB0203 Developing the skills of Academic Numeracy & IT
UB0203 Developing the skills of Academic Numeracy & IT Wardah Rosman
 
Ub0203 developing the skills of academic numeracy & it 2
Ub0203 developing the skills of academic numeracy & it 2Ub0203 developing the skills of academic numeracy & it 2
Ub0203 developing the skills of academic numeracy & it 2Wardah Rosman
 
Jb slideshow!!
Jb slideshow!!Jb slideshow!!
Jb slideshow!!zoiefuller
 
Presentación1
Presentación1Presentación1
Presentación1topillo1
 

Andere mochten auch (8)

Automated posting on facebook and twitter for IIMnet members
Automated posting on facebook and twitter for IIMnet membersAutomated posting on facebook and twitter for IIMnet members
Automated posting on facebook and twitter for IIMnet members
 
The New Data Security Risk
The New Data Security RiskThe New Data Security Risk
The New Data Security Risk
 
Exercicisdetransmissidemovimentambpolitges
Exercicisdetransmissidemovimentambpolitges Exercicisdetransmissidemovimentambpolitges
Exercicisdetransmissidemovimentambpolitges
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
UB0203 Developing the skills of Academic Numeracy & IT
UB0203 Developing the skills of Academic Numeracy & IT UB0203 Developing the skills of Academic Numeracy & IT
UB0203 Developing the skills of Academic Numeracy & IT
 
Ub0203 developing the skills of academic numeracy & it 2
Ub0203 developing the skills of academic numeracy & it 2Ub0203 developing the skills of academic numeracy & it 2
Ub0203 developing the skills of academic numeracy & it 2
 
Jb slideshow!!
Jb slideshow!!Jb slideshow!!
Jb slideshow!!
 
Presentación1
Presentación1Presentación1
Presentación1
 

Ähnlich wie Cs3430 lecture 16

Ähnlich wie Cs3430 lecture 16 (20)

PERL.ppt
PERL.pptPERL.ppt
PERL.ppt
 
Scalar data types
Scalar data typesScalar data types
Scalar data types
 
Perl 6 command line scripting
Perl 6 command line scriptingPerl 6 command line scripting
Perl 6 command line scripting
 
Ruby training day1
Ruby training day1Ruby training day1
Ruby training day1
 
enum_namespace.ppt
enum_namespace.pptenum_namespace.ppt
enum_namespace.ppt
 
Unit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxUnit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptx
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeString handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
 
Introduction To Python
Introduction To  PythonIntroduction To  Python
Introduction To Python
 
Perl
PerlPerl
Perl
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 
Python bible
Python biblePython bible
Python bible
 
UNIT 4 python.pptx
UNIT 4 python.pptxUNIT 4 python.pptx
UNIT 4 python.pptx
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Bioinformatica p4-io
Bioinformatica p4-ioBioinformatica p4-io
Bioinformatica p4-io
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptx
 
Pointers
PointersPointers
Pointers
 

Mehr von Tanwir Zaman

Mehr von Tanwir Zaman (14)

Cs3430 lecture 17
Cs3430 lecture 17Cs3430 lecture 17
Cs3430 lecture 17
 
Cs3430 lecture 14
Cs3430 lecture 14Cs3430 lecture 14
Cs3430 lecture 14
 
Cs3430 lecture 13
Cs3430 lecture 13Cs3430 lecture 13
Cs3430 lecture 13
 
Python lecture 12
Python lecture 12Python lecture 12
Python lecture 12
 
Python lecture 10
Python lecture 10Python lecture 10
Python lecture 10
 
Python lecture 09
Python lecture 09Python lecture 09
Python lecture 09
 
Python lecture 8
Python lecture 8Python lecture 8
Python lecture 8
 
Python lecture 07
Python lecture 07Python lecture 07
Python lecture 07
 
Python lecture 06
Python lecture 06Python lecture 06
Python lecture 06
 
Python lecture 04
Python lecture 04Python lecture 04
Python lecture 04
 
Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
 
Python lecture 02
Python lecture 02Python lecture 02
Python lecture 02
 
Python lecture 01
Python lecture 01Python lecture 01
Python lecture 01
 
Python lecture 11
Python lecture 11Python lecture 11
Python lecture 11
 

Kürzlich hochgeladen

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 

Kürzlich hochgeladen (20)

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 

Cs3430 lecture 16

  • 1. Python & Perl Lecture 16 Department of Computer Science Utah State University
  • 2. Outline ● Identifiers and scopes ● Arrays
  • 4. 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
  • 5. 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;
  • 6. 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;
  • 7. 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;
  • 8. 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
  • 9. 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";
  • 10. 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
  • 11. 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";
  • 12. 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.
  • 13. 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";
  • 14. 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
  • 15. 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";
  • 16. 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
  • 18. 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
  • 19. 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
  • 20. 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”
  • 22. 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
  • 23. 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
  • 25. 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
  • 26. 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);
  • 27. 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);
  • 28. 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 = ();
  • 29. 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);
  • 30. 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');
  • 31. 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')
  • 32. 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')
  • 33. 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
  • 35. 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
  • 37. Array Functions push, pop, unshift, shift
  • 38. 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
  • 39. Example: pop & push ● Display the following pattern of numbers * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  • 40. 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
  • 42. 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
  • 43. 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
  • 46. 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
  • 48. 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
  • 49. 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
  • 51. 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 $_
  • 53. 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.
  • 54. 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: $an"; $a = $a + 1; } value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19
  • 55. 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: $an"; $a = $a + 1; } value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14
  • 57. 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
  • 58. 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
  • 59. Reading & References ● http://perldoc.perl.org/ ● James Lee. Beginning Perl, 2nd Edition, APRESS ● Dietel, Dietel, Nieto, McPhie. Perl How to Program, Prentice Hall