String Perl:从文件读取后,如何检查数组列中存在的字的最大宽度?
我从一个文件中读取数据,然后再次写入另一个文件。所以在写作时,由于一些大字的对齐,后面的专栏会被扭曲。我希望对齐所有列,而不考虑其长度。我这里有一个。但问题是他们使用的是Perl模块String Perl:从文件读取后,如何检查数组列中存在的字的最大宽度?,string,perl,output,alignment,multiple-columns,String,Perl,Output,Alignment,Multiple Columns,我从一个文件中读取数据,然后再次写入另一个文件。所以在写作时,由于一些大字的对齐,后面的专栏会被扭曲。我希望对齐所有列,而不考虑其长度。我这里有一个。但问题是他们使用的是Perl模块Perl6::Form,我不想使用任何模块 #This the input file Hey! How Are You I AM FINEEE Thankyouuu 1 22 333 4444 对齐后,应如下所示: Hey! How Are You I AM FINEE
Perl6::Form
,我不想使用任何模块
#This the input file
Hey! How Are You
I AM FINEEE Thankyouuu
1 22 333 4444
对齐后,应如下所示:
Hey! How Are You
I AM FINEEE Thankyouuu
1 22 333 4444
已尝试代码(已更新)):
也许应该用下面的方法来做这项工作
use strict;
use warnings;
use feature 'say';
my @lines;
my @max_len;
while( <> ) {
next if /^#/;
chomp;
my @data = split;
push @lines, \@data;
my @length = map { length } @data;
@max_len = map { $max_len[$_] || $length[$_] } 0..$#length;
@max_len = map { $max_len[$_] < $length[$_] ? $length[$_] : $max_len[$_] } 0..$#length;
}
my @formats = map { '%-'. $_ . 's' } @max_len;
my $format = join ' ', @formats, "\n";
printf $format, @{$_} for @lines;
注意:可以将输出重定向到输出文件
script.pl file1.log>temp.log
将其放入文件program.pl
#!/usr/bin/perl
use warnings; use strict; my(@table,@len);
while(<>){
my @row = split /\s+/;
for my $col ( 0 .. $#row ){
my $l = length($row[$col]);
$len[$col] = $l if not defined$len[$col] or $l > $len[$col];
}
push @table, \@row;
}
my $format = join " ", map '%-'.$_.'s', @len;
printf "$format\n", @$_ for @table;
或许
chmod +x program.pl
cat inputfile.txt | ./program.pl > outputfile.txt
不要重新发明轮子。*NIX实用程序可以很好地处理这项任务(另请参见灯光注释) 示例: 按空格(制表符、空格等)拆分输入: 此处,
John Doe
被视为两个字段
在选项卡上拆分输入(将空白字段视为单个字段):
在这里,
John Doe
被视为一个字段。为什么不使用制表符?他们不会在文本编辑器中对齐文本,但它们会使其机器可读和由Excel打开。如果你不局限于Perl,你可以考虑使用<代码>列-T < /Cord>。@ AlexanderMashin,是的,使用Tab,然后生成一个选项卡受限的XLS是不错的选择。但是我再次生成了日志格式,这就是为什么需要对齐的原因。my@col\u lens=map{length}@rows代码>应获取当前行和列的长度。查找每列的最大值,查找文件的开头,并使用最大列宽printf()输出文件。@ССаа27,您能检查更新的部分吗?谢谢你。
Hey! How Are You
I AM FINEEE Thankyouuu
1 22 333 4444
#!/usr/bin/perl
use warnings; use strict; my(@table,@len);
while(<>){
my @row = split /\s+/;
for my $col ( 0 .. $#row ){
my $l = length($row[$col]);
$len[$col] = $l if not defined$len[$col] or $l > $len[$col];
}
push @table, \@row;
}
my $format = join " ", map '%-'.$_.'s', @len;
printf "$format\n", @$_ for @table;
perl program.pl inputfile.txt > outputfile.txt
chmod +x program.pl
cat inputfile.txt | ./program.pl > outputfile.txt
perl -le 'print join "\t", qw(Hey! How Are You); print join "\t", qw(I AM FINEEE Thankyouuu ), q{John Doe};' | \
column -t
Hey! How Are You
I AM FINEEE Thankyouuu John Doe
perl -le 'print join "\t", qw(Hey! How Are You); print join "\t", qw(I AM FINEEE Thankyouuu ), q{John Doe};' | \
column -t -s$'\t'
Hey! How Are You
I AM FINEEE Thankyouuu John Doe