我试图在二维数组中读取一个巨大的CSV文件,必须有一个更好的方法来分割线并一步保存在二维数组中:s干杯
my $j = 0;
while (<IN>)
{
chomp ;
my @cols=();
@cols = split(/,/);
shift(@cols) ; #to remove the first number which is a line header
for(my $i=0; $i<11; $i++)
{
$array[$i][$j] = $cols[$i];
}
$j++;
}
Run Code Online (Sandbox Code Playgroud)
fri*_*edo 12
CSV不是一件容易的事.不要自己解析.使用像Text :: CSV这样的模块,它可以正确快速地完成.
use strict;
use warnings;
use Text::CSV;
my @data; # 2D array for CSV data
my $file = 'something.csv';
my $csv = Text::CSV->new;
open my $fh, '<', $file or die "Could not open $file: $!";
while( my $row = $csv->getline( $fh ) ) {
shift @$row; # throw away first value
push @data, $row;
}
Run Code Online (Sandbox Code Playgroud)
这样可以很好地获取所有行@data,而无需担心自己解析CSV.
如果您发现自己正在使用 C 风格的 for 循环,那么您的程序设计很有可能得到改进。
while (<IN>) {
chomp;
my @cols = split(/,/);
shift(@cols); #to remove the first number which is a line header
push @array, \@cols;
}
Run Code Online (Sandbox Code Playgroud)
这假设您有一个可以用简单的方法处理的 CSV 文件split(即记录不包含嵌入的逗号)。