469,342 Members | 5,299 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,342 developers. It's quick & easy.

Parsing a CSV file into a Hash

7
Hi,
Im a new to perl and i hope there are people here that can help me!

I have a realy large file like this.
1,12,T,
2,13,B,
3,14,T,
4,15,B,

I want to use the 2nd and 3th column and put it into a hash like

with the 2nd column being the keys and the 3th column being the values.

This is what i have but i doesn't work!

open (data, 'data.csv');
my $hash_data = <data>;
my @hash_data = split (/,/, $hash_data);
@hash_Key = $hash_Data[1];
@hash_Values = $hash_Data[2];
%hash_data =($hash_Key => $hash_Values);
print %hash_data;

I hope someone can help me!

Iris
Feb 28 '07 #1
3 13483
arne
315 Expert 100+
Hi,
Im a new to perl and i hope there are people here that can help me!

I have a realy large file like this.
1,12,T,
2,13,B,
3,14,T,
4,15,B,

I want to use the 2nd and 3th column and put it into a hash like

with the 2nd column being the keys and the 3th column being the values.

This is what i have but i doesn't work!

open (data, 'data.csv');
my $hash_data = <data>;
my @hash_data = split (/,/, $hash_data);
@hash_Key = $hash_Data[1];
@hash_Values = $hash_Data[2];
%hash_data =($hash_Key => $hash_Values);
print %hash_data;

I hope someone can help me!

Iris
You could try something like
Expand|Select|Wrap|Line Numbers
  1. open DATA, "data.csv";
  2.  
  3. my %hash;
  4.  
  5. while( <DATA> ) {
  6.  
  7.     @elements = split /,/, $_;
  8.  
  9.     if( $elements[1] ne '' ) {
  10.         $hash{ $elements[1] } = $elements[2];
  11.     }
  12. }
  13.  
Feb 28 '07 #2
Iris83
7
Thanks this works!
Feb 28 '07 #3
@Iris83

Just another possibility:

Expand|Select|Wrap|Line Numbers
  1. open(DATA, "<", "data.csv") or die $!;
  2.  
  3. my %hash;
  4.  
  5. %hash = ( %hash, (split(/,/, $_))[1,2] ) while ( <DATA> );
Greetz, Doc
Feb 28 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by sp | last post: by
1 post views Thread by John Wright | last post: by
14 posts views Thread by mens libertina | last post: by
2 posts views Thread by joe2684 | last post: by
2 posts views Thread by amittewarii | last post: by
4 posts views Thread by subeen | last post: by
6 posts views Thread by whiteideal | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.