Perl Programming Test

This is a test to help us get a feel for your Perl programming abilities. There is no single correct way to answer the following questions. Rather, there are several different ways that will show your coding style and knowledge of Perl's peculiarities as a language. Try to answer the questions using your own knowledge, but if you need to refer to a manual, you may.

  1. Show at least two ways to convert the following string to upper case in Perl, and explain the subtle differences between each way:
    $foo
      = "Toast is yummy.";
    
  2. Write a program that reads in a tab-delimited text file and swaps the 2nd and 3rd columns. Given the following sample text:
    item	name	subcat	color	vendor
    407	king	2	red	Budgeco
    44	queen	3	blue	Bobcorp
    483	double	15	black	Jorgonix
    592	single	3	pink	Simonion
    290	none	99
    

    Your program should return data like this:

    item	subcat	name	color	vendor
    407	2	king	red	Budgeco
    

    etc.

  3. Write a small module that performs the function in question 2 based on a subroutine call like:
    swap_columns(1, 2);
    

    Extra credit:

  4. Rewrite the following Perl code in a more Perl-specific programming style. Take advantage of as many Perl shortcuts as you can to make the code shorter and/or easier to read:
    @words = ("good", "bad", "ugly", "nice");
    for ($i = 0; $i <= $#words; $i++) {
      printf("%s %s %s", "I have been very", $words[$i], "\n");
    }
    
  5. You have a hash with dictionary words as keys. Each value is a reference to an array containing the names of files that contain that word. Your hash looks like this:
    %words = ( "foo" => ["foodoc1", "foodoc2", "foodoc3"],
               "bar" => ["bardoc1", "bardoc2", "bardoc3"],
               "baz" => ["bazdoc1", "bazdoc2", "bazdoc3"],
               "qux" => ["quxdoc1", "quxdoc2", "quxdoc3"]
             );
    

    Write a Perl expression that returns the third document containing the word "bar".

  6. You have a string that is to be used as part of a filename. The string has come directly from the user and has not been processed in any way. The user is not authorized to have shell access. Write a regular expression that will "clean" the string so that the user cannot breach security and gain shell access or otherwise circumvent security when the program opens or otherwise accesses the file.

  7. Extra credit. Explain what the following program does, for all interesting values of $m.
    chomp ($m = <STDIN>);
    for ($i=($m==0?($m=12)==12:$m); $i<=$m; $i++) {
      print "Reporting for $i\n";
    }