Perl在不使用对象的情况下创建格式化表

时间:2012-12-06 14:18:05

标签: perl

我想简单地在表中输出一些结果,而不存在任何偏移问题。为了清晰起见,不要担心只是伪代码的foreach和值的输出。

print "\n  ______________________________________________________";
print "\n |                                                      |";
print "\n |                        Title                         |";
print "\n +______________________________________________________+";
print "\n |                          |                           |";
print "\n |          City            |          Size             |";
print "\n |__________________________|___________________________|";

#Sort by highest scores
################################
foreach (city, size)
{
print "\n | (city(value)";
print "| (size(value)";
}

任何想法?

2 个答案:

答案 0 :(得分:5)

它很少被使用,但Perl具有内置的能力来创建这些类型的forms

基本上,您使用规范来说明您希望如何格式化这些表,以及使用format语句放置这些表中的信息的位置。然后,使用Perl write语句写入该格式。您也可以指定表格的页眉和页脚。

答案 1 :(得分:2)

我建议你使用 substr 覆盖模板行的正确部分。

use strict;
use warnings;

my %data = (
  Birmingham  => 1_000_000,
  Bristol     => 430_000,
  Manchester   => 110_000,
);

print "  ______________________________________________________\n";
print " |                                                      |\n";
print " |                        Title                         |\n";
print " +______________________________________________________+\n";

my $template =
      " |                          |                           |\n";
print $template;

while (my ($city, $size) = each %data) {
  my $line = $template;
  substr $line, 12, length $city, $city;
  substr $line, 39, length $size, $size;
  print $line;
}

print " |__________________________|___________________________|\n";

<强>输出

  ______________________________________________________
 |                                                      |
 |                        Title                         |
 +______________________________________________________+
 |                          |                           |
 |          Bristol         |          430000           |
 |          Manchester      |          110000           |
 |          Birmingham      |          1000000          |
 |__________________________|___________________________|