********** July 9th lab - review of theSum.p code ********** ********** Two group exercises: writing functions ********** chaos:~/web/perl$ cat theSum.p <-------- Could also use more theSum.p ------------- # Written on Monday, July 9th, 2001 for 810:088 lab class session # and Tuesday followup lecture/discussion. # This program defines two different functions, theSum and theProduct # ------ ---------- # Filename: theSum.p sub theSum; sub theProduct; @a = (11, 22, 33, 44, 55); $numbers = join (" + ", @a); $numbers = "(" . $numbers . ")"; $answer = theSum(@a, $numbers); # Note: Two arguments are input # to theSum() function.... print "\nThe sum ($numbers) is $answer.\n"; $numbers = join (" * ", @a); print "\nThe product ($numbers) is " . theProduct(@a) . ".\n\n"; ########################################################################## # theSum is a Function (read Hour 8) or a Subroutine (read chapter 13) # # # # Input: Argument #1: A list (array) of numbers # # Argument #2: A string formatted list of the numbers, to echo # # out the values in whatever format the user wants # # # # Output: Returns the sum of the list of values, and # # prints to STDOUT the formatted list. # ########################################################################## sub theSum { print "\n ****** Entering theSum function ****** \n"; $string = pop @_; # remove the last element from the array @_ # this was the 2nd argument in the call. @array = @_; # what is left is the list of numbers passed # as the 1st argument in calling theSum(). $s = 0; print "\nThe popped value was ---> $string \n"; foreach $element (@array) { $s += $element; } print "\n ****** Leaving theSum and returning a value ****** \n"; return $s; } ######################################################################## # Function theProduct # # ---------- Input: An array of numeric values # # Output: Product of the values # # # ######################################################################## sub theProduct { @a = @_; $p = 1; foreach $value (@a) { $p = $p * $value; } return $p; } chaos:~/web/perl$ perl theSum.p ****** Entering theSum function ****** The popped value was ---> (11 + 22 + 33 + 44 + 55) ****** Leaving theSum and returning a value ****** The sum ((11 + 22 + 33 + 44 + 55)) is 165. The product (11 * 22 * 33 * 44 * 55) is 19326120. -------------------------------------------------------------------------- 1. Write a function that would return 1 (True) if the list a numbers is sorted into ascending order, and 0 (False) otherwise. if ( ascending(@a) ) { $m = "The list is sorted "; } else { $m = "The list is NOT sorted "; } $m .= "in ASCENDING order.\n"; print $m; 2. Write a function that would remove all of the negative numbers from the list. For example: @a = (11, -22, 33, -44, 55); @a = removeNegativeValues(@a); print "Here is array \@a with minus values gone: " . "@a \n";