I had a need to print the values of an array in vertical columns.
Input array:
one two three four five six seven eight nine ten
Output:
t s e h f f e i n o t r o i s v g i t n w e u v i e h n e e o e r e x n t e n
Here's the code I came up with to do it...
use strict; my @w_rows = qw(one two three four five six seven eight n +ine ten); # Rows rows_to_columns(\@w_rows, " ", 1); ############################################################ # Function: rows_to_columns # Purpose: Vertically print the input array # Example: rows_to_columns(\@array[,$pad[,$justify]]); ############################################################ sub rows_to_columns { my $r_rows = $_[0]; # Ref to input array my $w_pad = $_[1] || ' '; # Spacing between columns my $s_justify = $_[2] || 0; # Justify 0=top, 1=bottom return 0 unless (ref($r_rows) eq "ARRAY"); my @w_rows = @$r_rows; my %w_columns = (); my %w_col_rows = (); my $w_row_ix = 0; my $w_col_ix = 0; my $l_max_row = 0; my $w_row = ''; # Find the longest array element ($l_max_row) $w_row_ix = map { $l_max_row= (length($_) > $l_max_row) ? length($_) : $l_max_row; } @w_rows; ##################################### # Process input array ##################################### for ( $w_row_ix = 0; $w_row_ix <= $#w_rows; $w_row_ix++ ) { $w_row = ($s_justify) ? ' ' x ($l_max_row - length($w_rows[$w_row_ix +])) . $w_rows[$w_row_ix] : $w_rows[$w_row_ix] . ' ' x ($l_max_row - len +gth($w_rows[$w_row_ix])) ; # print "$w_row\n"; ################### # Reformat->columns ################### for ( $w_col_ix = 0; $w_col_ix < $l_max_row; $w_col_ix++ ) { my $w_char = substr($w_row,$w_col_ix,1); $w_columns{$w_col_ix} = "$w_columns{$w_col_ix}${w_pad}${w_ +char}"; } } ##################################### # Print input array - vertically ##################################### for my $key ( sort { $a <=> $b } keys %w_columns ) { print "$w_columns{$key}\n"; } return 1; }
Comments and constructive suggestions are welcome :)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Print array vertically (in columns)
by liverpole (Monsignor) on Sep 02, 2009 at 00:09 UTC | |
by perlofwisdom (Pilgrim) on Sep 03, 2009 at 16:16 UTC | |
|
Re: Print array vertically (in columns)
by bv (Friar) on Sep 04, 2009 at 17:17 UTC | |
|
Re: Print array vertically (in columns)
by stonecolddevin (Parson) on Sep 18, 2009 at 21:56 UTC |