我有一个打印文本文件的任务(包含标题和几行)。我设法编写了一个程序来打印文本文件中的几行。但我无法让我的代码打印表格标题。
#!/usr/bin/perl
use strict;
use warnings;
my $filename = 'c73p1avrfusevrmtop.txt';
open(my $fh, '<:encoding(UTF-8)', $filename)
or die "Could not open file '$filename' $!";
my $row = <$fh>;
while (my $row = <$fh>) {
chomp $row;
print "$row\n";
}
我有8列x 7,最后一列是空的。我想在每个对齐的列下打印我的行。我很遗憾无法附加图片,因为它需要10个声誉。
我为这个错误道歉。这是我所指的表格。
Type Name Rev Id ZZZ ID IP Group Date Released AA Category Project IDs
xxxxxComponent xyz_abc_1234LDO_c7rp1avrusevrmdtop xxxx_2_5 99ccccc1 ABC- RIP-xxxxx 2015-05-03 6:59:09 xxxx
xxxxxComponent xyz_abc_1234LDO_c7rp1avrusevrmdtop xxxx_2_5 99ccccc1 ABC RIP xxxxx 2015-05-03 6:59:09 xxxx
xxxxxComponent xyz_abc_1234LDO_c7rp1avrusevrmdtop xxxx_2_5 99ccccc1 ABC RIP xxxxx 2015-05-03 6:59:09 xxxx
答案 0 :(得分:4)
你忘了打印它。在下面的修复中,我为标题使用了一个单独的变量(即第一行),只是为了记录为什么我不在循环中打印它。
#!/usr/bin/perl
use strict;
use warnings;
# Create a file handle for the input file
my $filename = 'c73p1avrfusevrmtop.txt';
open(my $fh, '<:encoding(UTF-8)', $filename)
or die "Could not open file '$filename' $!";
# print header
my $header = <$fh>;
print $header;
# print rows
while (my $row = <$fh>) {
chomp $row;
print "$row\n";
}
以下是我希望采用的格式相同的代码:
#!/bin/env perl
use strict;
use warnings;
use autodie; # so I don't have to use the 'open or die' idiom
# Create a file handle for the input file
my $filename = 'c73p1avrfusevrmtop.txt';
open(my $fh, '<:encoding(UTF-8)', $filename);
# print header
my $header = readline $fh;
print $header; # note it still has a newline
# print rows
while (my $row = readline $fh) {
chomp $row;
print "$row\n";
}