我试图在二维数组中读取一个巨大的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++; }
解决方法
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; }
这将在@data中很好地获取所有行,而不必担心自己解析CSV.