packetstormer has asked for the wisdom of the Perl Monks concerning the following question:
Hello
I am having some more difficulties with hashes and arrays.
In a nutshell I have a hash with a unique ID for each key. I also have an array with the first element is always a unique ID. I am trying to iterate through the hash keys and foreach key check if it exists in the array. If it does I need to update the value of the hash (for that key) to include the values in the list after the first element (If you get me!!)
Here is what I have, and it works for one array, but as soon as start introducing multi-arrays the data gets skewed. Because the actual script pulls its data from a database it might be difficult to dump the data here but assume one hash called %ret and one array called @lines. Typically, the script will look like this:
my @line1 = ('_W9C2JJDCB','<P>This is the problem1.</P>','<P>This is r +es1</P>'); my @line2 = ('_W9C2JJDCB','<P>This is the problem2.</P>','<P>This is r +es2</P>'); my @line3 = ('_W9C2JJDCB','<P>This is the problem3.</P>','<P>This is r +es3</P>'); my @totlines; push (@totlines,\@line1); push (@totlines,\@line2); push (@totlines,\@line3); my @dir1 =('_W9C2JJDCB', '201200240', 'TEST: IGNORE', 'John Doe', 'Closed', 'HIP', 'email@email.com', 'email2@email.com', ); my %hash = ( '_W9C2JJDCB' => \@dir1); #At this point I have one hash (which may have many key/values) and on +e array which could have many array refs
Now, the problem is that once the hash grows to more than one key the loops starts polluting the values with other array elements.# So this is what I am trying to do for my $key(keys %hash) { my $value = $hash{$key}; my @arr = @$value; foreach my $u(@totlines) { if(@$u[0] == $key) { #print "$key @arr --- @$u\n"; push (@arr,@$u); $hash{$key} = \@arr; } } } print Dumper %ret;
I appreiciate this is really hard to even explain correctly but I am hoping some will see some flaw in my logic in the "for key" loop?
EDIT: Of course an IF statement somewhere might help - added IF statement
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Comparing Hash key with array
by InfiniteSilence (Curate) on Feb 02, 2012 at 17:21 UTC | |
|
Re: Comparing Hash key with array
by Anonymous Monk on Feb 02, 2012 at 16:28 UTC | |
by packetstormer (Monk) on Feb 02, 2012 at 16:44 UTC | |
by Anonymous Monk on Feb 02, 2012 at 17:00 UTC | |
by packetstormer (Monk) on Feb 02, 2012 at 17:21 UTC | |
|
Re: Comparing Hash key with array
by thundergnat (Deacon) on Feb 02, 2012 at 17:19 UTC | |
|
Re: Comparing Hash key with array
by Riales (Hermit) on Feb 02, 2012 at 17:21 UTC | |
by packetstormer (Monk) on Feb 02, 2012 at 17:25 UTC | |
by Riales (Hermit) on Feb 02, 2012 at 17:32 UTC | |
by packetstormer (Monk) on Feb 02, 2012 at 17:43 UTC | |
by Riales (Hermit) on Feb 02, 2012 at 17:50 UTC |