数组 – 读取CSV文件并保存为2 d数组

前端之家收集整理的这篇文章主要介绍了数组 – 读取CSV文件并保存为2 d数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在二维数组中读取一个巨大的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.

猜你在找的Perl相关文章