【发布时间】:2011-07-11 20:22:00
【问题描述】:
我在使用 Perl 的内置拆分功能时遇到了一点麻烦。我正在创建一个脚本来编辑 CSV 文件的第一行,该文件使用管道进行列分隔。下面是第一行:
KEY|H1|H2|H3
但是,当我运行脚本时,这是我收到的输出:
Col1|Col2|Col3|Col4|Col5|Col6|Col7|Col8|Col9|Col10|Col11|Col12|Col13|
我有一种感觉,Perl 不喜欢我使用变量来实际进行拆分这一事实,在这种情况下,变量是一个管道。当我用实际管道替换变量时,它可以按预期完美运行。使用管道分隔时,即使传入变量,我如何才能正确分割线?另外,作为一个愚蠢的警告,我没有权限从 CPAN 安装外部模块,所以我必须坚持使用内置函数和模块。
对于上下文,这是我的脚本的必要部分:
our $opt_h;
our $opt_f;
our $opt_d;
# Get user input - filename and delimiter
getopts("f:d:h");
if (defined($opt_h)) {
&print_help;
exit 0;
}
if (!defined($opt_f)) {
$opt_f = &promptUser("Enter the Source file, for example /qa/data/testdata/prod.csv");
}
if (!defined($opt_d)) {
$opt_d = "\|";
}
my $delimiter = "\|";
my $temp_file = $opt_f;
my @temp_file = split(/\./, $temp_file);
$temp_file = $temp_file[0]."_add-headers.".$temp_file[1];
open(source_file, "<", $opt_f) or die "Err opening $opt_f: $!";
open(temp_file, ">", $temp_file) or die "Error opening $temp_file: $!";
my $source_header = <source_file>;
my @source_header_columns = split(/${delimiter}/, $source_header);
chomp(@source_header_columns);
for (my $i=1; $i<=scalar(@source_header_columns); $i++) {
print temp_file "Col$i";
print temp_file "$delimiter";
}
print temp_file "\n";
while (my $line = <source_file>) {
print temp_file "$line";
}
close(source_file);
close(temp_file);
【问题讨论】: