Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Transpose a matrix of chars

by neniro (Priest)
on Jul 04, 2005 at 09:28 UTC ( [id://472184]=note: print w/replies, xml ) Need Help??


in reply to Transpose a matrix of chars

#!/usr/bin/perl use strict; use warnings; use List::Util qw/ max /; my @rows; push @rows, [split (/\s/, $_)] for (<DATA>); my $max_index = max map { scalar @$_ -1; } @rows; for my $r (0..$max_index) { for my $c (0..$#rows) { print $rows[$c]->[$r] || ' '; print ' '; } print "\n"; } __DATA__ A B C F G u b 1 T A R S 2 P

Replies are listed 'Best First'.
Re^2: Transpose a matrix of chars
by dirac (Beadle) on Jul 04, 2005 at 13:02 UTC
    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;
    
      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 $#$_ :)
      You could try:
      my $max_cols = pop @{[sort{$a <=> $b} map { @$_- 1 } @rows]};

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://472184]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2024-03-29 11:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found