Camel
Peter
Peter Campbell Smith

Good phones, phones good

Weekly challenge 110 — 26 April 2021

Week 110: 26 Apr 2021

Task 2

Task — Transpose file

You are given a text file, in which the first line names a number of attributes and each subsequent line lists these attributes for successive entities.

Write a script to transpose the contents of the given file, such that each line starts with an entity name, followed by the attributes of that entity.

Examples


Input:
name,age,sex
Mohammad,45,m
Joe,20,m
Julie,35,f
Cristina,10,f

Output:
name, Mohammad, Joe, Julie, Cristina
age, 45, 20, 35, 10
sex, m, m, f, f

Analysis

This is a simple matrix transpose operation. Each line of the input adds a single attribute to each line of the output.

More precisely, each line of the input is divided into $n comma-separated components, and these components are added, one to each output line. The output file thus has as many lines as the input has components per line, and vice versa.

Try it 

Try running the script with any input:



example:
carrot,red,root,boiled
lettuce,green,leaf,raw
potato,white,root,fried
banana,yellow,fruit,raw

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2021-04-26
use utf8;     # Week 110 - task 2 - Transpose file
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

transpose_file();

sub transpose_file {
    
    my ($j, $line, @fields, $f, @output);
    
    # read input
    $j = 0;
    say qq[\nInput:  ];
    while ($line = <DATA>) {
        print $line;
        chomp $line;
        
        # split into fields and add to lines of output
        @fields = split(',', $line);
        $output[$_] .= $fields[$_] . ',' for 0 .. @fields - 1;
        $j ++;
    }
    
    # show output
    say qq[\nOutput:];
    say substr($output[$_], 0, -1) for 0 .. @output - 1;
}

__DATA__
name,age,sex
Mohammad,45,m
Joe,20,m
Julie,35,f
Cristina,10,f

18 lines of code

I completed this challenge after the closing date
and it has not been submitted to GitHub

Output


Input:  
name,age,sex
Mohammad,45,m
Joe,20,m
Julie,35,f
Cristina,10,f

Output:
name,Mohammad,Joe,Julie,Cristina
age,45,20,35,10
sex,m,m,f,f

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain