tags:

views:

925

answers:

2

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

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.

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?

E.g.,

print $hsh{'foo1'}[4];
+6  A: 

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

#!/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
Sinan Ünür
Thank you very much!
YoDar
@Yohad you are welcome.
Sinan Ünür
+4  A: 

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.

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.

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.

Tony Miller
+1 for reinforcing the recommendation to use CPAN modules.
Sinan Ünür