Extra Credit Assignment

Extra Credit Assignment


This assignment is worth 15 exercise points to be credited against points that were taken off for lateness prior to December 7, 2000.

As we discussed a class or two ago, I've provided the solutions to your Perl exercises by putting multiple little sub-programs into a single file; for example, see p2_solutions.prl. If you want to try out these solutions, it can be annoying to have to cut and paste these snippets of program into files.

A better solution is to add some "if" statements in appropriate places, turning all the little programs in the file into one big program that runs only the piece of code you want it to. For example, you could turn a file containing

  #ex_02-3
  #Learning Perl Appendix A, Exercise 2.3
  print "First number: "; chomp($a = <STDIN>);
  print "Second number: "; chomp($b = <STDIN>);
  $c = $a * $b; print "Answer is $c.\n";

  #ex_02-4
  #Learning Perl Appendix A, Exercise 2.4
  print "String: "; $a = <STDIN>;
  print "Number of times: "; chomp($b = <STDIN>);
  $c = $a x $b; print "The result is:\n$c";
into a file containing
  #!/usr/imports/bin/prl

  # Change this value to select a different program to run
  $choice = 1; 

  if ($choice == 1) {
    #ex_02-3
    #Learning Perl Appendix A, Exercise 2.3
    print "First number: "; chomp($a = <STDIN>);
    print "Second number: "; chomp($b = <STDIN>);
    $c = $a * $b; print "Answer is $c.\n";
  }

  if ($choice == 2) {
    #ex_02-4
    #Learning Perl Appendix A, Exercise 2.4
    print "String: "; $a = <STDIN>;
    print "Number of times: "; chomp($b = <STDIN>);
    $c = $a x $b; print "The result is:\n$c";
  }

The main trick to this is knowing where the little sub-programs start and end, but that's not too difficult: you can rely on the fact that all the sub-programs start with a comment line beginning with "#ex_". Hint: also note that the start of a new sub-program means the end of the previous one! (Except for the last subprogram in the file, of course.)

Your job is to write a Perl program that takes the solutions file as its input, and writes out a new version of it modified as I've described above. I'm providing an example of the input (p2_solutions.prl) and an example of the output (p2_oneprogram.prl).

Regarding details, I don't care whether you read from STDIN or a file, and I don't care whether you create your output via STDOUT or via opening an output file. I also don't really care whether or not the formatting of the output is pretty, e.g. pretty indentation and blank lines don't really matter to me. What does matter is that the result be a valid, working Perl program with a global variable initialized at the top called $choice, with the first sub-program getting run when $choice equals 1, the second sub-program getting run when $choice equals 2, etc.

The due date for this extra credit assignment is the same as the due date for the final project.

Have fun!