Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Perl Exercise using References: Create a program that reads a tab separated file

ID: 657194 • Letter: P

Question

Perl Exercise using References:
Create a program that reads a tab separated file with numbers, ie 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. After reading 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.

1      2      3      4      5
6      7      8      9   10
11   12   13   14   15
16   17   18   19   20
21   22   23   24   25

Explanation / Answer

my @rows = (); my @transposed = (); # This is each row in your table push(@rows, [qw(0 1 2 3 4 5 6 7 8 9 10)]); push(@rows, [qw(6 7 3 6 9 3 1 5 2 4 6)]); for my $row (@rows) { for my $column (0 .. $#{$row}) { push(@{$transposed[$column]}, $row->[$column]); } } for my $new_row (@transposed) { for my $new_col (@{$new_row}) { print $new_col, " "; } print " "; }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote