in reply to Get CSV data and convert it to other format data dynamically.

Here is my input on it, which I am pretty new to hashes as well so please keep that in mind ;)

use strict; use warnings; use Data::Dumper; my %hash = (); my $i = 0; while (<DATA>) { chomp; my ( $sec_id, $Initial_shares ) = split( /,/, $_ ); $hash{secid}{$i} = $sec_id; $hash{init_sh}{$i} = $Initial_shares; $i++; } #print Dumper \%hash; foreach my $outter_key ( keys %hash ) { print "$outter_key => {\n"; while ( my ( $inner_key, $inner_value ) = each $hash{$outter_key} +) { print "\t\t" . qq('$inner_key') . " => " . qq('$inner_value') +. "\n"; } print "};\n\n"; } __DATA__ 002826,3777 0028262,3777 0028262,3777 0028262,3777 0028262,3777 0028262,3777

Outputs:

init_sh => { '4' => '3777' '1' => '3777' '3' => '3777' '0' => '3777' '2' => '3777' '5' => '3777' }; secid => { '4' => '0028262' '1' => '0028262' '3' => '0028262' '0' => '002826' '2' => '0028262' '5' => '0028262' };

This method looks like it would be a sure fire way to keep track of what belonged to what as well.

EDIT: I dont know why, but I thought OP was looking for a solution with hashes... anyway on a side note, while I was messing around with this, I did figure out another way to load modules haha;

EDIT: Updated code.

Replies are listed 'Best First'.
Re^2: Get CSV data and convert it to other format data dynamically.
by Tux (Canon) on Aug 25, 2015 at 06:44 UTC

    If you use Text::CSV_XS' csv function with the filter attribute, you don't also keep the CSV data and stream the required content right into the arrays:

    use 5.14.2; use warnings; use Text::CSV_XS qw(csv); my (@a, @b); my $aoa = csv ( in => *DATA, headers => "skip", filter => { 1 => sub { push @a, $_; 1 }, 2 => sub { push @b, $_; 0 }, }); { local $" = ", "; say "var secid = [@a]"; say "var Initial_shares = [@b]"; } __END__ secid,Initial_shares 002826,3777 0028262,3777 0028262,3777 0028262,3777 0028262,3777 0028262,3777

    var secid = [002826 0028262 0028262 0028262 0028262 0028262] var Initial_shares = [3777 3777 3777 3777 3777 3777]

    The entries in the filter will be used in ascending order. All but the last should return a true value. The last should return a false value to reject the record: You already stored all required data in the two arrays.

    update: Alternatively, you can put everything in a hash:

    my %h; my $aoa = csv ( in => *DATA, headers => "auto", filter => { 1 => sub { for my $f (keys %_) { push @{$h{$f}}, $_{$ +f} }; 0 }}, );

    { Initial_shares => [ 3777, 3777, 3777, 3777, 3777, 3777 ], secid => [ '002826', '0028262', '0028262', '0028262', '0028262', '0028262' ] }

    Enjoy, Have FUN! H.Merijn