在Perl中,如何編寫和讀取由密鑰和數組組成的CSV文件?

[英]In Perl, how can I write and read CSV file composed from a key and array?


I have a problem to write and read properly a CSV file composed of name(key) and array of values:

我有一個問題是要正確地編寫和讀取由名稱(鍵)和值數組組成的CSV文件:

testarray.csv

foo1 ,0,0,0,0,1
foo2 ,1,0,0,0,1
foo3 ,3,4,5,6,7
.
.
.

I need to represent that file as follows:

我需要表示該文件如下:

foo# will be the key and the five following numbers will be its array.

foo#將是關鍵,后面的五個數字將是它的數組。

What is the simple way to conduct that and to recall it for a use (not with Dumper)? How can I use a varible from an array of a specific key?

進行該操作並將其召回以供使用(不是使用Dumper)的簡單方法是什么?如何使用特定鍵的數組中的變量?

E.g.,

print $hsh{'foo1'}[4];

2 个解决方案

#1


Normally, I would recommend Text::xSV and/or Text::CSV but for such simple data, a straightforward join should work:

通常,我建議使用Text :: xSV和/或Text :: CSV,但對於這樣的簡單數據,直接連接應該有效:

#!/usr/bin/perl

use strict;
use warnings;

my %hash = (
    foo1 => [ 0, 0, 0, 0, 1 ],
    foo2 => [ 1, 0, 0, 0, 1 ],
    foo3 => [ 3, 4, 5, 6, 7 ],
);

for my $key ( sort keys %hash ) {
    print join( q{,}, $key, @{ $hash{$key} } ), "\n";
}

__END__

Output:

C:\Temp> ttt
foo1,0,0,0,0,1
foo2,1,0,0,0,1
foo3,3,4,5,6,7

Reading it in:

閱讀:

#!/usr/bin/perl

use strict;
use warnings;

my %hash;

while ( <DATA> ) {
    chomp;
    last unless /\S/;
    my ($key, @data) = split /,/;
    $hash{$key} = \@data;
}

print $hash{foo2}->[4], "\n";

__DATA__
foo1,0,0,0,0,1
foo2,1,0,0,0,1
foo3,3,4,5,6,7

Output:

C:\Temp> ttt
1

#2


Sinan Unur's solution is good and correct, but I think that the OP's problem is an XY Problem. He is specifically asking about reading and storing data from a CSV file. Since that seems to be the real goal, then the best solution is to make use of reuse and get Text::CSV installed in your Perl. It does the heavy lifting of dealing with CSV files, gives you ways to reference all the data, and provides a nice API while doing so.

Sinan Unur的解決方案是好的和正確的,但我認為OP的問題是XY問題。他特別詢問從CSV文件中讀取和存儲數據。由於這似乎是真正的目標,因此最好的解決方案是利用重用並在Perl中安裝Text :: CSV。它完成了處理CSV文件的繁重工作,為您提供了引用所有數據的方法,並提供了一個很好的API。

If that doesn't float your boat, you can try DBD::CSV which, in conjunction with DBI will give you the ability to use SQL to query/insert/update the CSV. If you're used to SQL, that is a nifty way to proceed as well.

如果這不會漂浮您的船,您可以嘗試DBD :: CSV,它與DBI一起使您能夠使用SQL查詢/插入/更新CSV。如果你已經習慣了SQL,那么這也是一種很好的方式。

Edit:

Based on simple nature of data, if you really want to roll your own, his solution is a good one, already gave it +1.

基於數據的簡單性,如果你真的想要自己推出,他的解決方案是一個很好的解決方案,已經給它+1了。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/07/09/72f4a7f972182f43e389130da3e88d6b.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com