Update: So some example code for you... This is an Array of Hash (AoH). You were on the right track realizing that you can't just push a ref to %imolecule. [@maxval] expands @maxval and then puts it into a new hunk memory that is an anonymous array (i.e. makes a "deep" copy). The hash can be handled in the same way. Any way, you can have a "molecule template" that you fill out and then push onto @allmolecules.%imolecule = ( 'maxval' => [@maxval], 'minval' => [@minval], 'range' => [@mp], 'label' => $molcount, 'peers' => '0', ); push @allmolecules, {%imolecule};
#!/usr/bin/perl -w use strict; use Data::Dumper; my @allmolecules; my @maxval = (11,12,13); my @minval = (1,2,3); my @mp = (1,13); my $molcount = 2; my %imolecule = ( 'maxval' => [@maxval], 'minval' => [@minval], 'range' => [@mp], 'label' => $molcount, 'peers' => '0', ); push @allmolecules, {%imolecule}; $molcount = 444; @maxval = (66, 78, 90); %imolecule = ( 'maxval' => [@maxval], 'minval' => [@minval], 'range' => [@mp], 'label' => $molcount, 'peers' => '0', ); push @allmolecules, {%imolecule}; my $n=1; foreach my $href (@allmolecules) { print "Molecule: ", $n++,":\n"; foreach my $key (sort keys %$href) { if (ref($href->{$key}) eq 'ARRAY') { print "$key @{$href->{$key}}\n"; } else { print "$key $href->{$key}\n"; } } print "\n"; } print "Data Dumper output is....\n"; print Dumper \@allmolecules; __END__ output: Molecule: 1: label 2 maxval 11 12 13 minval 1 2 3 peers 0 range 1 13 Molecule: 2: label 444 maxval 66 78 90 minval 1 2 3 peers 0 range 1 13 Data Dumper output is.... $VAR1 = [ { 'maxval' => [ 11, 12, 13 ], 'peers' => '0', 'minval' => [ 1, 2, 3 ], 'range' => [ 1, 13 ], 'label' => 2 }, { 'maxval' => [ 66, 78, 90 ], 'peers' => '0', 'minval' => [ 1, 2, 3 ], 'range' => [ 1, 13 ], 'label' => 444 } ];
In reply to Re: Help creating/printing array of hashes
by Marshall
in thread Help creating/printing array of hashes
by tomdbs98
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |