SlideShare uma empresa Scribd logo
1 de 59
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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...
 

Destaque

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
 

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

Semelhante a Cs3430 lecture 16

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

Mais de Tanwir Zaman

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

Último

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 

Último (20)

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

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