Cs3430 lecture 16

186 views

Published on

Published in: Education
  • Be the first to comment

  • Be the first to like this

Cs3430 lecture 16

  1. 1. Python & Perl Lecture 16 Department of Computer Science Utah State University
  2. 2. Outline ● Identifiers and scopes ● Arrays
  3. 3. Identifiers & Scopes
  4. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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
  17. 17. Arrays
  18. 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. 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. 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”
  21. 21. array_manip.pl Example
  22. 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. 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
  24. 24. array_manip2.pl Example
  25. 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. 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. 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. 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. 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. 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. 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. 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. 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
  34. 34. consec_array_slicing.pl Example
  35. 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
  36. 36. nonconsec_array_slicing.pl Example
  37. 37. Array Functions push, pop, unshift, shift
  38. 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. 39. Example: pop & push ● Display the following pattern of numbers * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  40. 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
  41. 41. push_pop.pl Example
  42. 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. 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
  44. 44. unshift_shift.pl Source Code
  45. 45. Array Manipulation
  46. 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
  47. 47. Example array_assignment.pl
  48. 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. 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
  50. 50. Example array_length.pl
  51. 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 $_
  52. 52. Examples array_foreach.pl foreach_expression.pl
  53. 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. 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. 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
  56. 56. EXIT & DIE
  57. 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. 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. 59. Reading & References ● http://perldoc.perl.org/ ● James Lee. Beginning Perl, 2nd Edition, APRESS ● Dietel, Dietel, Nieto, McPhie. Perl How to Program, Prentice Hall

×