Perl – 将带分隔符的文本文件放入带有选项卡的Excel文件中

rest一段时间后回到Perl,我一直在寻找一种方法,将一些制表符分隔的文本文件放入一个数组,然后放入一个Excel文件中; 基本上是为目录中的每个文本文件生成一个Excel选项卡。 通常文本文件是一个相似的格式。

下面的代码已经从例子中拼凑出来,通常会产生我所追求的。 但是,输出会忽略任何选项卡,并在一个string中打印所有文本(每行)。 我正在努力如何在代码中实现制表符分隔符。 我知道我将需要拆分文本文件,因为他们被推入到数组中。 我一直在玩哈希,但是我认为我对这个问题的看法太过分了,这很可能是我错过的一个明显的答案。

use warnings; use strict; use Cwd qw(abs_path); use Spreadsheet::WriteExcel; die "Log path ARG required " unless defined $ARGV[0]; my $path = abs_path( $ARGV[0] ); my $workbook = Spreadsheet::WriteExcel->new("resultsbook.xls"); chdir $path or die "no such directory: $!"; if ( -d $path ) { ## test if $path given is a directory opendir my $dir, $path or die "can't open the directory: $!"; while ( defined( my $file = readdir($dir) ) ) { chomp $file; next if $file eq '.' or $file eq '..'; (my $sheetname = $file) =~s/\.\w+?//; my $wrksheet = $workbook->add_worksheet($sheetname); $wrksheet->write_col( 0, 0, [ @{ readfile($file) } ] ); } } sub readfile { my $textfilecontent = []; open my $fh, '<', shift() or die "can't open file:$!"; while (<$fh>) { chomp; push @{$textfilecontent}, $_, $/; } return $textfilecontent; } 

在将它们推入@textfilecontentvariables之前,您需要使用tab(或任何分隔符)来分割这些行。 这里还有一些其他的小错误:

 use warnings; use strict; use Cwd qw(abs_path); use Spreadsheet::WriteExcel; die "Log path ARG required " unless defined $ARGV[0]; my $path = abs_path( $ARGV[0] ); my $workbook = Spreadsheet::WriteExcel->new("resultsbook.xls"); chdir $path or die "no such directory: $!"; if ( -d $path ) { ## test if $path given is a directory opendir my $dir, $path or die "can't open the directory: $!"; while ( defined( my $file = readdir($dir) ) ) { chomp $file; next if $file eq '.' or $file eq '..'; (my $sheetname = $file) =~s/\.\w+//; my $wrksheet = $workbook->add_worksheet($sheetname); $wrksheet->write_col( 0, 0, readfile($file)); } } sub readfile { my @textfilecontent = (); open my $fh, '<', shift() or die "can't open file:$!"; while (<$fh>) { chomp; push @textfilecontent, [split(/\t/)]; } return \@textfilecontent; }