Parsing a CSV file into a Hash

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Iris83
    New Member
    • Feb 2007
    • 7

    Parsing a CSV file into a Hash

    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
  • arne
    Recognized Expert Contributor
    • Oct 2006
    • 315

    #2
    Originally posted by Iris83
    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
    Code:
    open DATA, "data.csv";
    
    my %hash;
    
    while( <DATA> ) {
    
    	@elements = split /,/, $_;
    
    	if( $elements[1] ne '' ) {
    		$hash{ $elements[1] } = $elements[2];
    	}
    }

    Comment

    • Iris83
      New Member
      • Feb 2007
      • 7

      #3
      Thanks this works!

      Comment

      • docsnyder
        New Member
        • Dec 2006
        • 88

        #4
        @Iris83

        Just another possibility:

        Code:
        open(DATA, "<", "data.csv") or die $!;
        
        my %hash;
        
        %hash = ( %hash, (split(/,/, $_))[1,2] ) while ( <DATA> );
        Greetz, Doc

        Comment

        Working...