in reply to How to stuff space separated column into Hash

choroba nailed this one++. I thought that I'd show you that this can work both ways, array=>hash and hash=>array.

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $string = 'February 1 March 5 July 4'; my @result_of_split = split ' ', $string; print Dumper \@result_of_split; =prints: (@result_of_split) $VAR1 = [ 'February', '1', 'March', '5', 'July', '4' ]; =cut my %hash = @result_of_split; #assign array to hash print Dumper \%hash; =prints: (%hash) $VAR1 = { 'February' => '1', 'July' => '4', 'March' => '5' }; =cut my @array = %hash; #assign hash back to an array print Dumper \@array; =prints: (@array) back again $VAR1 = [ 'February', '1', 'March', '5', 'July', '4' ]; =cut
When assigning an array to a hash, you have to have an even number of elements, 2,4,6,8, etc. If warnings is enabled (and should be), you will get a warning "odd number of ...." if @array contains 3,5, etc number of elements.

Replies are listed 'Best First'.
Re^2: How to stuff space separated column into Hash
by dirtdog (Monk) on Aug 29, 2016 at 20:53 UTC

    thanks marshall

    Ideally, I'd like to use a Hash of Hashes and I have the following code

    while ( my @row = $sth->fetchrow_array() ) { print ">@row<\n"; ($key, $value) = split ' ', $row[1]; $HoH{$row[0]}{$key} = $value; } while ( ($client, $months) = each %HoH ) { print "$client: "; while ( ($month, $count) = each %$months ) { print "$month=$count "; } print "\n"; }

    the problem is the split to get the $key and $value only gets the first key->value pair. Is there a way to get all of the key-value pairs into the HoH?

    Thanks!

      I think I'm all set

      while ( my @row = $sth->fetchrow_array() ) { print ">@row<\n"; my %by_month = split ' ', $row[1]; $HoH{$row[0]} = \%by_month;

      This accomplishes my objective. Thanks again.

        Glad that you have something "that works".

        Since I see that you are using the DBI and SQL, I would use the power of SQL instead of trying to replicate this into a HOH. I actually was wondering what you did with for example 'IBM' as element 0. You can get the unique names of the companies, IBM,Oracle, etc. and then run SQL queries to get those company specific results.

        It looks like you may be trying to translate the entire SQL DB into a HoH memory array? I am quite sure that this will work for a spreadsheet. However for a big DB, that won't work and is not necessary.

        It appears to me that you need some more DBI "kung foo".