печатать содержимое массива в столбцах переменной ширины - PullRequest
4 голосов
/ 26 августа 2011

Я хочу изменить свой код таким образом, чтобы столбец расширялся, чтобы вместить данные.

Ниже приведен пример разбитой строки

+========+=========+===============+=============+=============+
| Record | Cluster | Current Build | Current Use | Environment |
+--------+---------+---------------+-------------+-------------+
| 3      | 1       | v44           | v44 Live (currently - new company cluster)| PROD        |
+--------+---------+---------------+-------------+-------------+

Вот код (kludgy), который я использую

sub printData {
   if (@_) {
      # print the data grid top border
      printf ("%10s%10s%15s%14s%14s",'+'.('=' x 8).'+',('=' x 9).'+',('=' x 15).'+',('=' x 13).'+',('=' x 13).'+');
      print "\n";
      # print the data grid column titles
      printf ("%-9s%-10s%-16s%-14s%-15s",'| Record ','| Cluster ','| Current Build ','| Current Use ','| Environment |');
      print "\n";

      # print out each row of data
      foreach my $rows (@_) {

         # print the data grid demarcation border
         printf ("%10s%10s%15s%14s%14s",'+'.('-' x 8).'+',('-' x 9).'+',('-' x 15).'+',('-' x 13).'+',('-' x 13).'+');
         print "\n";

         # print each data cell
         printf ("%-9s",'| '.$rows->{'Record ID#'});
         printf ("%-10s",'| '.$rows->{'Cluster'});
         printf ("%-16s",'| '.$rows->{'Current Build'});
         printf ("%-14s",'| '.$rows->{'Current Use'});

            # calculate the length of the last column
            my $length = length($rows->{'Environment'});

            # calculate how many spaces to add to the last column
            # the title of this column uses 15 characters (including '|' and spaces)
            # we already used three of those spaces for 2 '|' characters  and 1 leading space
            # so 15 - 3 = 12 
            # then subtract the length of the return string from 12
            my $spaces = 12 - $length;

         # we print the last data cell plus the padding spaces calculated above
         printf ("%-15s",'| '.$rows->{'Environment'}.(' ' x $spaces).'|');
         print "\n";
      }

      # we print the bottom data grid border
      printf ("%10s%10s%15s%14s%14s",'+'.('=' x 8).'+',('=' x 9).'+',('=' x 15).'+',('=' x 13).'+',('=' x 13).'+');
      print "\n";
    }
   else {  
      if ($debug) {
         print "trouble with printData subroutine\n";
      }
      return 0;
    }
}

Ответы [ 4 ]

9 голосов
/ 26 августа 2011

Text :: Table отрегулирует ширину столбца в соответствии с данными.

3 голосов
/ 26 августа 2011

Вы должны предварительно отсканировать данные, получить максимальную ширину каждого поля, а затем построить строки форматирования.

2 голосов
/ 26 августа 2011

Я не знаком ни с одним из предложенных модулей, поэтому, если они не будут работать так, как вам хотелось бы, я бы сделал так, как предложил Mouse Food, и предварительно просканировал данные, чтобы получить максимальную ширину в каждомколонка.Эти максимальные ширины будут затем использоваться в строке формата при выводе.Если возможно, было бы более эффективно получить это максимальное значение при построении массива, а не повторять его дважды в конце.

Приведенный ниже код перебирает весь массив, чтобы найти максимальную длину столбца, ноэто должно быть легко адаптировано, если вы рассчитываете это по ходу дела.Кроме того, я списал это с манжеты и не проверял, но это должно дать вам идею.

my %maximums = {
    "Record ID#" => 0,
    "Cluster" => 0,
    "Current Build" => 0,
    "Current Use" => 0
};

# calculate the maximum length of the values in each column
foreach my $row (@_) {
    foreach my $col (keys %maximums) {
        my $col_length = length($row->{$col});
        $maximums{key} = $col_length if ($col_length > $maximums{$col});
    }
}

# Generate a format string using the maximum column widths.  Other format strings
# may be generated in this loop for the other parts of the table.  Alternatively
# you could probably transform the one string and replace the characters in it.
my $row_format = "|";
foreach my $col (keys %maximums) {
    $row_format .= " %-",$maximums{$key},"s |";
}
$row_format .= "\n";

# Print your headers and borders here, using the other format strings that you
# would calculate above (where $row_format is generated).

# Print each row in the table
foreach my $row (@_) {
    printf($row_format, $row->{"Record ID#"}, $row->{"Cluster"},
        $row->{"Current Build"}, $row->{"Current Use"});
}
2 голосов
/ 26 августа 2011

Text :: SimpleTable :: AutoWidth чрезвычайно прост и менее сложен, чем Text :: Table.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...