
Nick Hillier - https://unsplash.com/photos/assorted-numbers-photography-yD5rv8_WzxA
The following script performs the transposition of a matrix in Perl. Launched without arguments, the program transpose.pl prints the syntax for execution. In this case, we get the following output:
Usage: transpose.pl [ -p ] datafile -p prints original matrix
The script requires one or two arguments. At least one valid file must be provided. The ‘-p’ option is optional and allows the original matrix to be printed to the terminal.
Create a sample matrix inside a file called ‘matrix’:
a b c d e f g h i j k l m n o
Now we can run the script by giving the name of the file we just created as an argument. Remember to give execute permissions to the file:
$ ./transpose.pl matrix a f k b g l c h m d i n e j o
Executed with the ‘-p’ option, we get the following result:
$ ./transpose.pl -p matrix Original matrix a b c d e f g h i j k l m n o Transpose matrix a f k b g l c h m d i n e j o
Below is the complete code:
#!/usr/bin/perl use strict; if ( @ARGV < 1 || @ARGV > 2 ) { print "Usage: transpose.pl [ -p ] datafile\n"; print " -p prints original matrix\n"; exit; } my ($r, @data, $n, $datafile, $print_original); if ($ARGV[0] eq '-p') { $print_original = 1; $datafile = $ARGV[1]; } elsif ($ARGV[1] eq '-p') { $print_original = 1; $datafile = $ARGV[0]; } else { $print_original = 0; $datafile = $ARGV[0]; } if ($print_original) { print "Original matrix\n"; } open(IN, $datafile); $r = 0; while (<IN>) { next if ( /^\#/ || /^\%/ ); chop; my @a = split(/\s+/); $n = 0; foreach (@a) { $data[$n][$r] = $a[$n]; if ($print_original) { print "$data[$n][$r] "; } $n++; } if ($print_original) { print "\n"; } $r++; } close(IN); if ($print_original) { print "\nTranspose matrix\n"; } for (my $i = 0; $i < $n; $i++) { for (my $j = 0; $j < $r; $j++) { print "$data[$i][$j] "; } print "\n"; }