aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJörg Sommrey <28217714+jo-37@users.noreply.github.com>2021-04-26 20:35:57 +0200
committerJörg Sommrey <28217714+jo-37@users.noreply.github.com>2021-04-29 18:06:13 +0200
commit9dee88820f7b3a018c51028607f45781fc0ce695 (patch)
tree4aa3acfd053b6c57069c3b95f423162dfebf0a8e
parentf4f3d93f551953a75aecef48689cf599b60cd55e (diff)
downloadperlweeklychallenge-club-9dee88820f7b3a018c51028607f45781fc0ce695.tar.gz
perlweeklychallenge-club-9dee88820f7b3a018c51028607f45781fc0ce695.tar.bz2
perlweeklychallenge-club-9dee88820f7b3a018c51028607f45781fc0ce695.zip
Solution to task 2
-rwxr-xr-xchallenge-110/jo-37/perl/ch-2.pl71
1 files changed, 71 insertions, 0 deletions
diff --git a/challenge-110/jo-37/perl/ch-2.pl b/challenge-110/jo-37/perl/ch-2.pl
new file mode 100755
index 0000000000..a833da13f1
--- /dev/null
+++ b/challenge-110/jo-37/perl/ch-2.pl
@@ -0,0 +1,71 @@
+#!/usr/bin/perl -s
+
+use v5.16;
+use Test2::V0;
+use experimental qw(signatures postderef);
+
+our $examples;
+
+run_tests() if $examples; # does not return
+
+die <<EOS unless @ARGV;
+usage: $0 [-examples] [file ...]
+
+-examples
+ run the examples from the challenge
+
+file ...
+ file(s) to be transposed. Multiple files are concatenated first,
+ then transposed.
+
+EOS
+
+
+### Input and Output
+
+{
+ local $, = ',';
+ # perlvar states:
+ # passing "\*ARGV" as a parameter to a function that expects a
+ # filehandle may not cause your function to automatically read the
+ # contents of all the files in @ARGV.
+ # It seems to work, though.
+ say @$_ for transpose_file(\*ARGV);
+}
+
+
+### Implementation
+
+# Read lines from the given filehandle, split them at commas (chopping
+# newlines) and push the parts onto a list of arrays.
+sub transpose_file ($fh) {
+ my @tr;
+ while (<$fh>) {
+ my @part = split /,|\n/;
+ while (my ($i, $v) = each @part) {
+ push $tr[$i]->@*, $v;
+ }
+ }
+
+ @tr;
+}
+
+
+### Examples and tests
+
+sub run_tests {
+ open my $fh, '<', \(<<EOS =~ s/^ +//gmr);
+ name,age,sex
+ Mohammad,45,m
+ Joe,20,m
+ Julie,35,f
+ Cristina,10,f
+EOS
+ is [transpose_file($fh)], [
+ [qw(name Mohammad Joe Julie Cristina)],
+ [qw(age 45 20 35 10)],
+ [qw(sex m m f f)]], 'example';
+
+ done_testing;
+ exit;
+}