Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topic 3: Lists and arrays CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 3, pages 40-55, 86-91, 135-138 Programming Perl 3rd edition.

Similar presentations


Presentation on theme: "Topic 3: Lists and arrays CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 3, pages 40-55, 86-91, 135-138 Programming Perl 3rd edition."— Presentation transcript:

1 Topic 3: Lists and arrays CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 3, pages 40-55, 86-91, 135-138 Programming Perl 3rd edition pages 69-76, 116-120, 658, 682 perldata, perlvar manpages

2 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 2 In this topic  Arrays  Lists  List and array functions ► printing, sorting and reversing lists ► adding and removing array elements  Context  Iterating over lists ► for and foreach  Default argument $_  Arrays  Lists  List and array functions ► printing, sorting and reversing lists ► adding and removing array elements  Context  Iterating over lists ► for and foreach  Default argument $_

3 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 3 Arrays  Perl variables which can hold multiple scalars  Each element identified by an integer index ► starting at 0 ► index written inside square brackets  Perl variables which can hold multiple scalars  Each element identified by an integer index ► starting at 0 ► index written inside square brackets $item[0]$item[1]$item[2]$item[3]$item[4]$item[5] -423.14undef"Dog" reference 1e-10 Llama3 pages 40-42; Camel3 pages 8-10, 72-75; perldata manpage

4 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 4 Arrays  Arrays grow as necessary ► assigning to $array[99] makes the array at least 100 elements long –unassigned array elements in between return undef –unassigned array elements beyond end also return undef  $#array returns highest index ► equal to size of array - 1  Negative indices count from end of array ► $array[-1] is same as $array[$#array] ► $array[-5] is same as $array[$#array - 4]  Arrays grow as necessary ► assigning to $array[99] makes the array at least 100 elements long –unassigned array elements in between return undef –unassigned array elements beyond end also return undef  $#array returns highest index ► equal to size of array - 1  Negative indices count from end of array ► $array[-1] is same as $array[$#array] ► $array[-5] is same as $array[$#array - 4] Llama3 pages 42-43; Camel3 page 53

5 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 5 Lists  A list is an expression containing an ordered sequence of scalars ► arrays are variables which contain list data  List literal elements separated by commas ► and usually surrounded by parentheses ► (-5.3, 42, "porcupine", $a+10)  Some functions take list parameters ► print ("Hello ", $name, "\n");  Can also assign to a list ► corresponding elements are assigned ► ($one, $two) = ($two, $one); # Swap  A list is an expression containing an ordered sequence of scalars ► arrays are variables which contain list data  List literal elements separated by commas ► and usually surrounded by parentheses ► (-5.3, 42, "porcupine", $a+10)  Some functions take list parameters ► print ("Hello ", $name, "\n");  Can also assign to a list ► corresponding elements are assigned ► ($one, $two) = ($two, $one); # Swap Llama3 pages 40-41, 43; Camel3 pages 8-10, 72-75; perldata manpage

6 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 6 Arrays and lists  A list literal is an expression containing an ordered sequence of scalars ► lifetime of list literal is the statement containing it  An array is a variable containing a list value ► lifetime of array is determined by variable’s scope (local, global)  Using an array in an expression returns a list  Assigning a list to an array changes the array’s entire value  A list literal is an expression containing an ordered sequence of scalars ► lifetime of list literal is the statement containing it  An array is a variable containing a list value ► lifetime of array is determined by variable’s scope (local, global)  Using an array in an expression returns a list  Assigning a list to an array changes the array’s entire value Llama3 pages 40-41, 43; Camel3 pages 72-75; perldata manpage

7 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 7 Arrays and lists  Verbose way to initialize an array $animal[0] = "Dog"; $animal[1] = "Cat"; $animal[2] = "Wildebeest";  Shorter way to type this using a list ($animal[0], $animal[1], $animal[2]) = ("Dog", "Cat", "Wildebeest");  Even shorter, using qw (“quote word”) operator ► automatically breaks up intervening text into words separated by white space ($animal[0], $animal[1], $animal[2]) = qw(Dog Cat Wildebeest);  Verbose way to initialize an array $animal[0] = "Dog"; $animal[1] = "Cat"; $animal[2] = "Wildebeest";  Shorter way to type this using a list ($animal[0], $animal[1], $animal[2]) = ("Dog", "Cat", "Wildebeest");  Even shorter, using qw (“quote word”) operator ► automatically breaks up intervening text into words separated by white space ($animal[0], $animal[1], $animal[2]) = qw(Dog Cat Wildebeest); Llama3 pages 43-46; Camel3 pages 72-75; perldata manpage

8 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 8 Arrays  To refer to an entire array, write @array ► means ($array[0], $array[1],..., $array[$#array]) ► @ instead of $ –$ is single-element marker –@ is multiple-element marker ► No square brackets  Can initialize arrays ► @animal = ("Dog", "Cat", "Wildebeest"); ► @animal = qw(Dog Cat Wildebeest);  Can copy arrays ► @zoo = @animal;  Can clear arrays ► @victim = (); # Empty list  To refer to an entire array, write @array ► means ($array[0], $array[1],..., $array[$#array]) ► @ instead of $ –$ is single-element marker –@ is multiple-element marker ► No square brackets  Can initialize arrays ► @animal = ("Dog", "Cat", "Wildebeest"); ► @animal = qw(Dog Cat Wildebeest);  Can copy arrays ► @zoo = @animal;  Can clear arrays ► @victim = (); # Empty list Llama3 pages ; Camel3 pages 72-75; perldata manpage

9 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 9 Arrays  Arrays and scalars occupy different namespaces ► @x, $x[... ] refer to array variable @x ► $x refers to scalar variable $x ► changing one has no effect on the other  Arrays and array elements interpolate into double-quoted strings like scalars ► @days = qw(Sun Mon Tue Wed Thu Fri Sat); ► print "Days are @days\n"; # With spaces between ► print "Thank God it's $days[5]!\n";  Arrays cannot contain arrays ► because lists cannot contain lists ► arrays are “flat” data structure ► @weekdays = qw(Mon Tue Wed Thu Fri); ► @days = ("Sun", @weekdays, "Sat"); # 7 elements  Arrays and scalars occupy different namespaces ► @x, $x[... ] refer to array variable @x ► $x refers to scalar variable $x ► changing one has no effect on the other  Arrays and array elements interpolate into double-quoted strings like scalars ► @days = qw(Sun Mon Tue Wed Thu Fri Sat); ► print "Days are @days\n"; # With spaces between ► print "Thank God it's $days[5]!\n";  Arrays cannot contain arrays ► because lists cannot contain lists ► arrays are “flat” data structure ► @weekdays = qw(Mon Tue Wed Thu Fri); ► @days = ("Sun", @weekdays, "Sat"); # 7 elements Llama3 pages 47-48; Camel3 pages 12, 65-66

10 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 10 List functions  print ► prints each element ► print ("Hello ", $name, "\n");  sort ► returns an alphabetically sorted list ► print sort ("c", "a", "t"); # Prints act ► @items = sort @items; # In-place sort  reverse ► returns a list with the elements in reverse order ► @countdown = reverse "Liftoff", 1, 2, 3;  print ► prints each element ► print ("Hello ", $name, "\n");  sort ► returns an alphabetically sorted list ► print sort ("c", "a", "t"); # Prints act ► @items = sort @items; # In-place sort  reverse ► returns a list with the elements in reverse order ► @countdown = reverse "Liftoff", 1, 2, 3; Llama3 page 50; Camel3 chapter 29; perlfunc manpage

11 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 11 Array functions  push, pop ► adds elements to or removes an element from the right hand side of an array ► @array = (1, 2, 3, 4); ► push @array, 5; # Now 1, 2, 3, 4, 5 ► $five = pop @array; # Now 1, 2, 3, 4  unshift, shift ► adds elements to or removes an element from the left hand side of an array ► unshift like push, shift like pop  push, pop ► adds elements to or removes an element from the right hand side of an array ► @array = (1, 2, 3, 4); ► push @array, 5; # Now 1, 2, 3, 4, 5 ► $five = pop @array; # Now 1, 2, 3, 4  unshift, shift ► adds elements to or removes an element from the left hand side of an array ► unshift like push, shift like pop Llama3 pages 46-47; Camel3 chapter 29; perlfunc manpage

12 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 12 Timeout # Reindeer games. # Original list of reindeer. @reindeer = qw(Dasher Dancer Prancer Vixen Comet Cupid Donner Blitzen); # Rudolph, with your nose so bright... unshift @reindeer, "Rudolph"; # Add to front. # Sort the list, then reverse it. @reindeer = reverse sort @reindeer; # Print them out. Prints: # Vixen Rudolph Prancer Donner Dasher # Dancer Cupid Comet Blitzen print "@reindeer\n"; # Reindeer games. # Original list of reindeer. @reindeer = qw(Dasher Dancer Prancer Vixen Comet Cupid Donner Blitzen); # Rudolph, with your nose so bright... unshift @reindeer, "Rudolph"; # Add to front. # Sort the list, then reverse it. @reindeer = reverse sort @reindeer; # Print them out. Prints: # Vixen Rudolph Prancer Donner Dasher # Dancer Cupid Comet Blitzen print "@reindeer\n";

13 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 13 Context  Recall difference between > and gt ► a > b forces a and b to be treated as numbers ► a gt b forces a and b to be treated as strings ► Even if a and b are exactly the same Perl code!  Similar thing happens with scalars and lists ► 5 + stuff expects stuff to be a scalar ► sort stuff expects stuff to be a list  Context is the expectation of the number (one, many) of an expression based on surrounding code ► + (expects one thing) applies scalar context to its arguments ► sort (expects many things) applies list context to its arguments  Recall difference between > and gt ► a > b forces a and b to be treated as numbers ► a gt b forces a and b to be treated as strings ► Even if a and b are exactly the same Perl code!  Similar thing happens with scalars and lists ► 5 + stuff expects stuff to be a scalar ► sort stuff expects stuff to be a list  Context is the expectation of the number (one, many) of an expression based on surrounding code ► + (expects one thing) applies scalar context to its arguments ► sort (expects many things) applies list context to its arguments Llama3 pages 51-52; Camel3 pages 69-70, perlfunc manpage

14 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 14 Context  Some operators/functions need a scalar ► length, +, rand,., if / while condition ► apply scalar context on their arguments  Some operators/functions need a list ► print, sort ► apply list context on their arguments  Some operators/functions can do both ► = –if left hand side is scalar, apply scalar context –if left hand side is list or array, apply list context  Some operators/functions need a scalar ► length, +, rand,., if / while condition ► apply scalar context on their arguments  Some operators/functions need a list ► print, sort ► apply list context on their arguments  Some operators/functions can do both ► = –if left hand side is scalar, apply scalar context –if left hand side is list or array, apply list context Llama3 page 51

15 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 15 Context  Some functions/operators return different things depending on the context they are in ► –in scalar context returns the next line of input –in list context returns a list of all remaining lines ► arrays –in list context return all their elements –in scalar context return number of elements (size of array) ► expressions returning a scalar –in scalar context return the scalar –in list context return a one-element list containing the scalar ► user-defined subroutines can use wantarray function to learn what context they were called in  Some functions/operators return different things depending on the context they are in ► –in scalar context returns the next line of input –in list context returns a list of all remaining lines ► arrays –in list context return all their elements –in scalar context return number of elements (size of array) ► expressions returning a scalar –in scalar context return the scalar –in list context return a one-element list containing the scalar ► user-defined subroutines can use wantarray function to learn what context they were called in Llama3 pages 52-53; Camel3 pages 69-70, 76

16 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 16 Context  Can force scalar context on an expression using scalar keyword ► print scalar @days; # Prints 7  Never need to force list context on an expression ► surrounding code already provides list context when needed  Can force scalar context on an expression using scalar keyword ► print scalar @days; # Prints 7  Never need to force list context on an expression ► surrounding code already provides list context when needed Llama3 pages 52-53; Camel3 pages 69-70, 76

17 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 17 Context  What use is context? ► English also uses context in this way –Where is the reindeer? (He’s here) –Where are the reindeer? (They’re here, and here, and...) ► Allows you to write more compact code –because the number (one, many) is implied by the surrounding code ► Allows you to write more readable code –because the code can focus on the logic rather than having to express semantic meaning in unnecessary syntax ► Allows you to detect some logic errors –where a number mismatch occurs –Where is the dogs? (Huh? One or many?)  What use is context? ► English also uses context in this way –Where is the reindeer? (He’s here) –Where are the reindeer? (They’re here, and here, and...) ► Allows you to write more compact code –because the number (one, many) is implied by the surrounding code ► Allows you to write more readable code –because the code can focus on the logic rather than having to express semantic meaning in unnecessary syntax ► Allows you to detect some logic errors –where a number mismatch occurs –Where is the dogs? (Huh? One or many?)

18 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 18 Timeout # Using context for fun and profit: # printing the input lines in reverse order. # Read in all input lines. @lines = ; # Note list context. # Reverse the array. @backwards = reverse @lines; # Print out the result. print @backwards; # Or, even more compactly, this one-liner: # print reverse ; # Using context for fun and profit: # printing the input lines in reverse order. # Read in all input lines. @lines = ; # Note list context. # Reverse the array. @backwards = reverse @lines; # Print out the result. print @backwards; # Or, even more compactly, this one-liner: # print reverse ;

19 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 19 for statement for (initializer; condition; increment) { # initializer code executed once before loop. # Block is executed while condition is true. # increment code always executed before # end of each iteration. } Llama3 pages 34-35, 128-129, 132,133; Camel3 pages 114-115; perlsyn manpage condition evaluated in scalar context braces still compulsory

20 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 20 foreach statement foreach $var (list) { # First time through loop, # $var = first element of list. # Second time through loop, # $var = second element of list. # Stops when list is exhausted. } Llama3 pages 34-35, 128-129, 132,133; Camel3 pages 114-115; perlsyn manpage iterator variable, uses $_ if omitted list of scalars to iterate through (parentheses compulsory)

21 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 21 Timeout # Totalling a list of numbers using for. # Read input lines until EOF. @data = ; # Iterate over every element in @data. # Note use of @data in scalar context (size). for ($count = 0; $count < @data; $count++) { chomp $data[$count]; $total += $data[$count]; } # Print result. Print "Total is $total\n"; # Totalling a list of numbers using for. # Read input lines until EOF. @data = ; # Iterate over every element in @data. # Note use of @data in scalar context (size). for ($count = 0; $count < @data; $count++) { chomp $data[$count]; $total += $data[$count]; } # Print result. Print "Total is $total\n";

22 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 22 Timeout # Totalling a list of numbers using foreach. # Read input lines until EOF. @data = ; # Iterate over every element in @data. # Also could have eliminated @data with: # foreach $number ( ) foreach $number (@data) { chomp $number; $total += $number; } # Print result. Print "Total is $total\n"; # Totalling a list of numbers using foreach. # Read input lines until EOF. @data = ; # Iterate over every element in @data. # Also could have eliminated @data with: # foreach $number ( ) foreach $number (@data) { chomp $number; $total += $number; } # Print result. Print "Total is $total\n";

23 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 23 The default argument $_  Many Perl functions/operators use special variable $_ if a variable isn’t explicitly named ► print; –same as print $_; ► chomp; –same as chomp $_; ► uc –same as uc $_ ► sqrt –same as sqrt $_ ► foreach iterator ► while ( ) –same as while (defined ($_ = )) –special case, only applies to inside while condition  Many Perl functions/operators use special variable $_ if a variable isn’t explicitly named ► print; –same as print $_; ► chomp; –same as chomp $_; ► uc –same as uc $_ ► sqrt –same as sqrt $_ ► foreach iterator ► while ( ) –same as while (defined ($_ = )) –special case, only applies to inside while condition Llama3 pages 49, 86-88; Camel3 pages 658, 682, chapter 29; perlvar, perlfunc manpages

24 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 24 The default argument $_  Using $_ can make a program both shorter and clearer ► don’t have to think up iterator variable names ► can keep short loops clear of clutter  Using $_ can make a program both shorter and clearer ► don’t have to think up iterator variable names ► can keep short loops clear of clutter while (defined ($line = )) { print $line; } while ( ) { print; } “While there’s input...” “... print it.” print while ( ); using expression modifier

25 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 25 Expression modifiers  Can rewrite if, unless, while, until and foreach more compactly ► only if body is single statement ► braces, parentheses not needed ► sometimes a more natural way to phrase code  Can rewrite if, unless, while, until and foreach more compactly ► only if body is single statement ► braces, parentheses not needed ► sometimes a more natural way to phrase code if (condition) { statement; } statement if condition; Llama3 pages 130-131; Camel3 pages 112-113 Normal if statement As expression modifier

26 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 26 Covered in this topic  Arrays  Lists  List and array functions ► printing, sorting and reversing lists ► adding and removing array elements  Context ► scalar and list context  Iterating over lists ► for and foreach  Default argument $_  Expression modifiers  Arrays  Lists  List and array functions ► printing, sorting and reversing lists ► adding and removing array elements  Context ► scalar and list context  Iterating over lists ► for and foreach  Default argument $_  Expression modifiers

27 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 27 Going further  References ► nested data structures ► Topic 11  map and grep ► applying an operation across every element of an array ► Camel3 pages 740-741, 730; Llama3 pages 236-238  References ► nested data structures ► Topic 11  map and grep ► applying an operation across every element of an array ► Camel3 pages 740-741, 730; Llama3 pages 236-238

28 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 28 Next topic  Subroutines  Local variables  Command line  Subroutines  Local variables  Command line Llama3 chapter 4 Camel3 pages 80-83, 217-233, 659, 742-745 perlsub manpage


Download ppt "Topic 3: Lists and arrays CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 3, pages 40-55, 86-91, 135-138 Programming Perl 3rd edition."

Similar presentations


Ads by Google