How to turn an array of words into an array containing word characters in order?

I have an array of an unknown number of words with an unknown maximum length. I need to convert it to another array, basically turning it into an array of columns. so with this source array:

@original_array = ("first", "base", "Thelongest12", "justAWORD4");

The resluting array will be:

@result_array = ("fbTj","iahu","rses","selt","t oA","  nW","  gO","  eR","  sD","  t4","  1 ","  2 ");

In fact, I will have the following:

fbTj
iahu
rses
selt
t oA
  nW
  gO
  eR
  sD
  t4
  1
  2

I need to do this to create a table, and these words are the table headers. I hope I have made it clear and appreciate the help you are ready to give.

I tried it with split function, but I keep messing it up ...

EDIT: Hello everyone, thanks for all the tips and suggestions! I learned a lot from all of you, therefore, above my head. However, I found tchrist's answer more convenient, maybe because I come from c, C # background ... :)

+5
4

, . , :

$ cat /tmp/a
first
base
Thelongest12
justAWORD4

$ rot90 /tmp/a
fbTj
iahu
rses
selt
t oA
  nW
  gO
  eR
  sD
  t4
  1 
  2 

:

$ cat ~/scripts/rot90
#!/usr/bin/perl 
# rot90 - tchrist@perl.com

$/ = '';

# uncomment for easier to read, but not reversible:
### @ARGV = map { "fmt -20 $_ |" } @ARGV;

while ( <> ) {
    chomp;
    @lines = split /\n/;
    $MAXCOLS = -1;
    for (@lines) { $MAXCOLS = length if $MAXCOLS < length; }
    @vlines = ( " " x @lines ) x $MAXCOLS;
    for ( $row = 0; $row < @lines; $row++ ) {
        for ( $col = 0; $col < $MAXCOLS; $col++ ) {
            $char = ( length($lines[$row]) > $col  )
                    ? substr($lines[$row], $col, 1) 
                    : ' ';
            substr($vlines[$col], $row, 1) = $char;
        }
    }
    for (@vlines) {
        # uncomment for easier to read, but again not reversible
        ### s/(.)/$1 /g;
        print $_, "\n";
    }
    print "\n";
}
+5
use strict;
use warnings;
use 5.010;
use Algorithm::Loops 'MapCarU';

my @original_array = ("first", "base", "Thelongest12", "justAWORD4");
my @result_array = MapCarU { join '', map $_//' ', @_ } map [split //], @original_array;
+7
use strict;
use warnings;
use List::Util qw(max);

my @original_array = ("first", "base", "Thelongest12", "justAWORD4");
my @new_array = transpose(@original_array);

sub transpose {
    my @a = map { [ split // ] } @_;
    my $max = max(map $#$_, @a);
    my @out;
    for my $n (0 .. $max) {
        $out[$n] .= defined $a[$_][$n] ? $a[$_][$n] : ' ' for 0 .. $#a;
    }
    return @out;
}
+1
source

This is easy to do with a simple single-line interface:

perl -le'@l=map{chomp;$m=length if$m<length;$_}<>;for$i(0..$m-1){print map substr($_,$i,1)||" ",@l}'
0
source

All Articles