我试图了解 PERL 程序的错误。我有一个逗号分隔的文件,我想将每行的内容提取到一个单独的文本文件中,使用每行中第一个字段的内容作为文件名。
下面的程序正是这样做的,除了它跳过了 csv 文件的第一行。我试图通过添加几个打印命令来确定错误的来源。第 22 行的打印命令显示第一行是由第 21 行的命令读取的。但是,一旦 foreach 循环开始,第一行就不会打印。
我不太确定这个问题。我很感激任何帮助!
#!/usr/bin/perl
# script that takes a .csv file (such as that exported from Excel) and
# extracts the contents of each row into a separate text file, using the first column as the filename
# original source: http://www.tek-tips.com/viewthread.cfm?qid=1516940
# modified 3/14/12
# usage = ./export_rows.pl <yourfilename>.csv
use warnings;
use strict;
use Text::CSV_XS;
use Tie::Handle::CSV;
unless(@ARGV) {
print "Please supply a .csv file at the command line! For example, export_rows.pl myfile.csv\n";
exit;
}
my $fh = Tie::Handle::CSV->new(file => $ARGV[0],
header => 0);
my @headers = @{scalar <$fh>};
print "$headers[0]\n\n";
foreach my $csv_line (<$fh>) {
print "$csv_line->[0]\n";
open OUT, "> $csv_line->[0].txt" or die "Could not open file $csv_line->[0].txt for output.\n$!";
for my $i (1..$#headers) {
print OUT "$csv_line->[$i]\n";
}
close OUT;
}
close $fh;