Honourable Monks,
I need some powerful expressions in order to reduce code and avoiding intermediate variables or importing modules.
Suppose an array of strings which are to be printed as a matrix. The array is
my (@b) = qw(un deux trois quatre jedan dva tri tcheteri one two three );
First, how do I find the biggest string length? Does anybody have any command shorter then
my ($max) = sort {$b <=> $a} map length, @a;
Secondly, I want the array printed or displayed in columns as "tight" as possible and _justified left_. I don't manage justifying left with sprintf(). Let's choose 4 columns. Knowing $max, the shortest I manage is:
my $col=4; for(@b){ $_ = substr($_ . ' ' x $max, 0, $max +1)} @a = @b; for (;@a;){print splice (@a, 0, $col),"\n"}
An awful solution because I destroy the array and the aliasing substr($_ . ' ' x $max, 0, $max +1) is horrible. Better solutions are welcome :-) Finally, I want to "transpose" the previous display, or to "shuffle" it. The best I find is
@a = @b; my @c; for (;@a;){ my @b = splice (@a, 0, $col); map {push @{$c[$_]}, $b[$_]; } (0 .. $#b); } map {print @$_,"\n"} @c;
Really disgusting. I want prettier code. The code in one slurp:
use strict; use warnings; my (@a) = my (@b) = qw(un deux trois quatre jedan dva tri tcheteri on +e two three ); print "@a\n"; my ($max) = sort {$b <=> $a} map length, @a; print "max=$max\n"; my $col=4; for(@b){ $_ = substr($_ . ' ' x $max, 0, $max +1)} @a = @b; for (;@a;){print splice (@a, 0, $col),"\n"} print "\ntrasnsposed\n\n"; @a = @b; my @c; for (;@a;){ my @b = splice (@a, 0, $col); map {push @{$c[$_]}, $b[$_]; } (0 .. $#b); } map {print @$_,"\n"} @c;
Thank you for looking at this!

In reply to Printing an array columnwise or rowwise by logen

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.