Lesson 10: Perl References and Advanced Data Structures

Prev Index Next

Required reading
There is no good chapters in the text books about this subject. Read here instead.

Subjects covered

  • Semi-advanced use of hashes.
  • Subroutine parameters re-visited - $_[0]....
  • Perl hard references with the \ operator.
  • Testing what datatype a reference points with ref.

Necessary files to complete this exercise
To download the files to your system, just press the Shift key while you left click on the blue link. Follow the instructions.

All the following exercises have to be done in Perl

  1. Make a subroutine that removes duplicates from a list. The list (array) has to be passed to the subroutine as a reference and the array must be cleaned "in place". The subroutine should NOT return a value and you should not make any temporary arrays. Use it to improve 6.4. It is a stated goal the you must use a minimum of memory to perform the task.
  2. Time to combine 10.1 and 9.4; Make a subroutine that removes duplicates from a list. If the list is passed as an array, then behaviour should be like 9.4, i.e. return a clean list. If the list is passed as a reference to an array then behaviour should be like 10.1, i.e. clean the given array in place. Again the goal is to use a minimum of memory to perform the task. Example:
    @tab = &rmdup(@tab); # pass-by-value
    &rmdup(\@tab); # pass-by-reference
  3. Create a program that reads a tab separated file with numbers, matrix.dat, (to be understood as a matrix) and stores the numbers in a matrix-like hash (keys are indices, .i.e. "$i,$j"). The program should be able to figure out how many rows and columns the matrix has. Having read the matrix from file it should now transpose it (rows to columns and columns to rows) and in the end print the transposed matrix to the screen. Important: Construct a subroutine like &transpose($rows, $columns, \%matrix), which does not return a value (matrix), but transposes the matrix given to it by reference without making a new matrix in the subroutine but by changing the input matrix via the reference. The subroutine has to work with references only, no global variables or returned values/hashes.
    Optional: For added difficulty make the subroutine work without the $rows and $columns information.
    Hint: Also make a subroutine that prints a given matrix. That will be useful underway. Check out Wikipedia's entry on transposing a matrix.

This page was last updated         by Peter Wad Sackett, pws@cbs.dtu.dk