in reply to Array of Hashes population
Is that the hash is flattened into a list, and the hash structure is lost. Wrapping %tmp in curly brackets i.e. '{' and '}' turns %tmp into an anonymous hash and that preserves the hash structure.push @data, %tmp;
Code where you can see all this (play with the push statement) is given below:push @data, { %tmp }; and later .. print $data[0]->{COMPONENT};
#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my $file = "<DATA>"; my @columns = ( "ONE", "TWO", "THREE", "FOUR", "FIVE" ); my @AoH = read_dat($file); print Data::Dumper->Dump(\@AoH); print "\n\nArray of hash element: ", $AoH[0]->{"THREE"}, "\n"; sub read_dat { my $file = shift; my @data = (); for my $line( <DATA> ) { next unless $line =~ m/\w+/; my @line = split (",", $line); my $i = 0; my %tmp; foreach my $col (@columns){ $tmp{$col} = $line[$i]; $i++; } push @data, { %tmp }; } return @data; } __DATA__ 0,1,2,3,4 1,2,3,4,5 2,3,4,5,6 3,4,5,6,7
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Array of Hashes population
by TGI (Parson) on Mar 06, 2008 at 19:56 UTC |