簡體   English   中英

讀取CSV文件並保存為2 d陣列

[英]Read CSV file and save in 2 d array

我試圖在二維數組中讀取一個巨大的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。

如果您發現自己正在尋找C風格的循環,那么您的程序設計很有可能得到改進。

while (<IN>) {
    chomp;

    my @cols = split(/,/); 
    shift(@cols); #to remove the first number which is a line header

    push @array, \@cols;
}

這假設您有一個可以使用簡單split處理的CSV文件(即記錄中不包含嵌入的逗號)。

旁白:您可以使用以下方法簡化代碼:

my @cols = split /,/;

你對$array[$col][$row]賦值使用了一個不尋常的下標順序; 它使生活變得復雜。 根據數組中的列/行分配順序,我認為沒有更簡單的方法。


替代方案:如果你要顛倒數組中的下標順序( $array[$row][$col] ),你可以考慮使用:

use strict;
use warnings;

my @array;
for (my $j = 0; <>; $j++) # For testing I used <> instead of <IN>
{
    chomp;
    $array[$j] = [ split /,/ ];
    shift @{$array[$j]};   # Remove the line label
}

for (my $i = 0; $i < scalar(@array); $i++)
{
    for (my $j = 0; $j < scalar(@{$array[$i]}); $j++)
    {
        print "array[$i,$j] = $array[$i][$j]\n";
    }
}

樣本數據

label1,1,2,3
label2,3,2,1
label3,2,3,1

樣本輸出

array[0,0] = 1
array[0,1] = 2
array[0,2] = 3
array[1,0] = 3
array[1,1] = 2
array[1,2] = 1
array[2,0] = 2
array[2,1] = 3
array[2,2] = 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM