in reply to Re: Transpose a matrix of chars
in thread Transpose a matrix of chars

I rewrite your code without use List::Util qw/ max /:
#!/usr/bin/perl -w
use strict;
my @rows; 
push @rows, [split (/\s/, $_)] while (<DATA>);
my @nn = sort{$a <=> $b} map { @$_- 1 } @rows ;
my $max_cols = pop @nn;

for my $r (0..$max_cols) {
   for my $c (0..$#rows) { 
		$_ = $rows[$c]->[$r] ;
		print if defined;
   }
   print "\n";
}


__DATA__
A B C F G
u b 
1 T A R S 2 P
but I don't understand why this:
my $max_cols = pop sort{$a <=> $b} map { @$_- 1 } @rows ;
doesn't work and I must do this:
my @nn = pop sort{$a <=> $b} map { @$_- 1 } @rows ;
my $max_cols = pop @nn;

Replies are listed 'Best First'.
Re^3: Transpose a matrix of chars
by ysth (Canon) on Jul 04, 2005 at 22:42 UTC
    pop only works on an array, not a list; try a list slice:
    my $max_col = (sort {$a <=> $b} map $#$_, @rows)[-1];
    though in this particular case, you can just reverse the sort and use a list assignment:
    my ($max_col) = sort {$b <=> $a} map $#$_, @rows;
    Nit: I think of "max_cols" as being maximum number of columns found, but you are wanting one less than that, the maximum column index, so I called it max_col instead. And I think @$_ - 1 is pretty ugly compared to the elegant $#$_ :)
Re^3: Transpose a matrix of chars
by neniro (Priest) on Jul 04, 2005 at 13:31 UTC
    You could try:
    my $max_cols = pop @{[sort{$a <=> $b} map { @$_- 1 } @rows]};