Announcements: HW1 graded Monday HW2 due next Wednesday (late by Friday) Hard copies of HW2 available now Quiz on Feb. 13th (tentatively) Today: Lists (Arrays) sort "return valves" foreach examples indexing @A = (1,2,7,3,-1,9) @A2 = reverse @A A2 is (9,-1,3,7,2,1) A is still (1,2,7,3,-1,9), thus reverse does NOT change A. Sorting arrays: @A = ("abc" , "xyz" , "ged"); @A2 = sort @A; [sorts in ASCll-betical order] @A2 is ("abc" , "ged" , "xyz") [A is still unchanged] @A3 = (3,1,6,7,10); @A4 = sort @A3; @A3 is still the same @A4 is (1,10,3,6,7) [does NOT treat string as numbers] To sort numerically: @A5 = sort {$a <=> $b} @A3; [this will sort numerically in ascending order] @A5 is (1,3,6,7,10) @A6 = sort {$b <=> $a} @A3; [this will sort numerically in descending order] @A6 is (10,7,6,3,1) @A7 = sort {$a cmp $b} @A; [same as sort @A] @A7 is ("abc" , "xyz" , "ged") @A8 = sort {$b cmp $a} @A; [sorts text in descending order] @A8 is ("xyz" , "ged" , "abc") Don't try : sort {$a > $b} @A3 [will not do wht you want it to do] Example: User enter strings until they enter "q". Print out a sorted list of strings. Solution: $Str = ""; @List = (); while ($Str ne "q") { print 'Enter a string or "q": '; $Str = <> chomp $Str; if ($Str ne "q") { push @List,$Str; } } @List = sort @List; print "@List\n"; Looping through an array: @A = ("abc" , "xyz" , "ged") foreach $Var (@A) { } [will go through each one of the values in the list] Example: Print elements of array on separate lines. Solution: $Str = ""; @List = (); while ($Str ne "q") { print 'Enter a string or "q": '; $Str = <> chomp $Str; if ($Str ne "q") { push @List,$Str; } } @List = sort @List; foreach $Str (@List) { print "$Str\n"; } Example: Find largest number in an array (using foreach). Solution: @A = (....); $Big = -1000000; Foreach $Num(@A) { if ($Num > $Big) { $Big = $Num; } } print "$Big\n"; Example: Given an array of strings @A, and a string $Str, is $Str in @A? Solution: Foreach $Str2 (@A) { if ($Str eq $Str2) { print "I\n"; } }