topic 3: lists and arrays cse2395/cse3395 perl programming learning perl 3rd edition chapter 3,...

28
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

Upload: bernadette-nash

Post on 06-Jan-2018

222 views

Category:

Documents


1 download

DESCRIPTION

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] undef"Dog" reference 1e-10 Llama3 pages 40-42; Camel3 pages 8-10, 72-75; perldata manpage

TRANSCRIPT

Page 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

Topic 3: Lists and arrays

CSE2395/CSE3395Perl 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

Page 2: 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

2Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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 $_

Page 3: 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

3Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Arrays 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]

-42 3.14 undef "Dog" reference 1e-10

Llama3 pages 40-42; Camel3 pages 8-10, 72-75; perldata manpage

Page 4: 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

4Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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]

Llama3 pages 42-43; Camel3 page 53

Page 5: 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

5Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

Llama3 pages 40-41, 43; Camel3 pages 8-10, 72-75; perldata manpage

Page 6: 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

6Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

Llama3 pages 40-41, 43; Camel3 pages 72-75; perldata manpage

Page 7: 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

7Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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);

Llama3 pages 43-46; Camel3 pages 72-75; perldata manpage

Page 8: 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

8Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

Llama3 pages ; Camel3 pages 72-75; perldata manpage

Page 9: 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

9Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

Llama3 pages 47-48; Camel3 pages 12, 65-66

Page 10: 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

10Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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;

Llama3 page 50; Camel3 chapter 29; perlfunc manpage

Page 11: 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

11Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

Llama3 pages 46-47; Camel3 chapter 29; perlfunc manpage

Page 12: 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

12Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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 Blitzenprint "@reindeer\n";

Page 13: 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

13Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

Llama3 pages 51-52; Camel3 pages 69-70, perlfunc manpage

Page 14: 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

14Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

Page 15: 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

15Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Context Some functions/operators return different things

depending on the context they are in► <STDIN>

– 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

Page 16: 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

16Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

Llama3 pages 52-53; Camel3 pages 69-70, 76

Page 17: 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

17Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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?)

Page 18: 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

18Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Timeout# Using context for fun and profit:# printing the input lines in reverse order.

# Read in all input lines.@lines = <STDIN>; # Note list context.

# Reverse the array.@backwards = reverse @lines;

# Print out the result.print @backwards;

# Or, even more compactly, this one-liner:# print reverse <STDIN>;

Page 19: 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

19Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

Page 20: 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

20Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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)

Page 21: 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

21Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Timeout# Totalling a list of numbers using for.

# Read input lines until EOF.@data = <STDIN>;

# 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";

Page 22: 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

22Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Timeout# Totalling a list of numbers using foreach.

# Read input lines until EOF.@data = <STDIN>;

# Iterate over every element in @data.# Also could have eliminated @data with:# foreach $number (<STDIN>)foreach $number (@data){ chomp $number; $total += $number;}

# Print result.Print "Total is $total\n";

Page 23: 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

23Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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 (<STDIN>)

– same as while (defined ($_ = <STDIN>))– special case, only applies to <...> inside while condition

Llama3 pages 49, 86-88; Camel3 pages 658, 682, chapter 29; perlvar, perlfunc manpages

Page 24: 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

24Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

while (defined ($line = <STDIN>)){ print $line;}

while (<STDIN>){ print;}

“While there’s input ...”

“... print it.”

print while (<STDIN>);using expression

modifier

Page 25: 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

25Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

if (condition){ statement;}

statement if condition;

Llama3 pages 130-131; Camel3 pages 112-113

Normal if statement

As expression modifier

Page 26: 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

26Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

Page 27: 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

27Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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

Page 28: 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

28Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Next topic Subroutines Local variables Command line

Llama3 chapter 4Camel3 pages 80-83, 217-233, 659, 742-745perlsub manpage