2011-08-25 4 views
4

데이터를 수용하기 위해 열이 넓어 지도록 코드를 수정하고 싶습니다. 다음은 가변 너비 열에 배열 내용 인쇄

깨진 행 다음

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

의 예를 들어 내가

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; 
    } 
} 
+0

대신 Text :: Table을 찾아 내려고했습니다. –

답변

9

Text::Table은 데이터에 맞게 열 너비를 조정합니다.

3

을 (미봉책) 코드를 사용하고있다 당신이 가지고있는 데이터는 최대 폭을받을 수 있나요 사전 검사 각 필드의 형식 문자열을 작성하십시오.

2

Text::SimpleTable::AutoWidth은 매우 간단하며 Text :: Table보다 덜 까다 롭습니다.

+0

Moose를 사용하는 것이 좋습니다. 아직 설치하지 않은 경우 CPAN의 절반을 가져옵니다. 무스에서 new() 만 상속받은 경우 마우스를 사용하지 않으시겠습니까? RET

2

내가 이미 제안한 모듈 중 하나에 익숙하지 않아서 원하는대로 작동하지 않으면 마우스 음식으로 제안하고 미리 스캔하여 최대 너비가되도록 스캔합니다. 각 열. 이 최대 너비는 출력 할 때 형식 문자열에 사용됩니다. 가능하다면 배열을 만드는 동안이 최대 값을 얻는 것이 최종적으로 두 번 반복하는 것보다 효과적 일 것입니다.

아래의 코드는 전체 열 길이를 찾기 위해 전체 배열을 반복하지만, 사용자가 계산할 때 쉽게 계산할 수 있어야합니다. 또한, 나는 이것을 커프에서 썼다. 그리고 그것을 테스트하지 않았다. 그러나 그것은 당신에게 생각을 주어야한다.

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"}); 
}