1

我有一个任务要求我打印出一些排序列表并用“\t”分隔字段。我已经完成了作业,但我似乎无法让所有字段都与制表符对齐。下面是一些输出,超过一定长度的名称会破坏字段。我怎样才能仍然使用 '\t' 并让所有东西都对齐那么多空间?

open(DOB, ">dob.txt") || die "cannot open $!";

# Output name and DOB, sorted by month
foreach my $key (sort {$month{$a} <=> $month{$b}} keys %month)  
{ 
    my @fullName = split(/ /, $namelist{$key});
    print DOB "$fullName[1], $fullName[0]\t$doblist{$key}\n";
}
close(DOB);

电流输出:

Santiago, Jose   1/5/58
Pinhead, Zippy   1/1/67
Neal, Jesse      2/3/36
Gutierrez, Paco  2/28/53
Sailor, Popeye   3/19/35
Corder, Norma    3/28/45
Kirstin, Lesley  4/22/62
Fardbarkle, Fred             4/12/23
4

1 回答 1

2

您需要知道有多少个空格相当于一个制表符。然后,您可以计算出每个条目涵盖了多少个选项卡。

如果制表符占用 4 个空格,则以下代码有效:

$TAB_SPACE = 4;
$NUM_TABS  = 4;
foreach my $key (sort {$month{$a} <=> $month{$b}} keys %month) {
    my @fullName = split(/ /, $namelist{$key});
    my $name = "$fullName[1], $fullName[0]";

    # This rounds down, but that just means you need a partial tab
    my $covered_tabs = int(length($name) / $TAB_SPACE);

    print $name . ("\t" x ($NUM_TABS - $covered_tabs)) . $doblist{$key}\n";
}

您需要知道要填充多少个制表符,但您可以通过与实际打印行非常相似的方式来解决这个问题。

于 2013-11-07T16:22:56.383 回答