tomdbs98 has asked for the wisdom of the Perl Monks concerning the following question:
Hi, I am currently working on my first perl program. Which would make this my first post here at perlmonks so take it easy on me :P
I am stuck on attempting to make an array of hashes, where each hash has both arrays(of scalars) and scalars within it. There error I am currently getting is:
Can't coerce array into hash at calcoverlap.pl line 222.
1 is {
here is where I set up the hash:this part gets looped for as many times as there are molecules in a file. I reuse the '%imolecule' hash each loop, clearing it and refilling it with data. At the end of the loop I try to print out the hash array to see if it worked at all:%imolecule = ( 'maxval' => [@maxval], 'minval' => [@minval], 'range' => [@mp], 'label' => $molcount, 'peers' => '0', ); push @allmolecules, %imolecule;
The above error indicates that the problem lies with this line of code:for $i ( 1 .. $#allmolecules ) { print "$i is { "; for $field ( keys %{ $allmolecules[$i] } ) { #line 222 if (ref($allmolecules[$i]{$field}) eq "ARRAY") { print "$field=@{$allmolecules[$i]{$field}}"; } else { print "$field=$allmolecules[$i]{$field}"; } } print "}\n"; }
which would mean the allmolecules[i] isn't a hash.for $field ( keys %{ $allmolecules[$i] } ) {
Does anyone know what my mistake would be?
Also, since I reuse the imolecule hash each loop, I can't push it as a reference, but is there a better way to be doing it?
Appreciate any help :)
-tom
Update: Wow, thanks for the quick responses. I didn't realize that using {} would allocate new memory for my hash each round, allowing me to use the same hash name each loop. Dumper was very useful for me as well. I will definitely read that suggested material so my next problem won't be so easy for you guys to solve ;). Thanks again :)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Help creating/printing array of hashes
by AR (Friar) on May 27, 2010 at 15:53 UTC | |
|
Re: Help creating/printing array of hashes
by toolic (Bishop) on May 27, 2010 at 16:00 UTC | |
|
Re: Help creating/printing array of hashes
by NetWallah (Canon) on May 27, 2010 at 17:43 UTC | |
|
Re: Help creating/printing array of hashes
by Marshall (Canon) on May 27, 2010 at 17:17 UTC | |
|
Re: Help creating/printing array of hashes
by planetscape (Chancellor) on May 27, 2010 at 21:48 UTC |