Hello hungrysumo79, and welcome to the Monastery!
In addition to the problem identified by beech — using an assignment (=) where a comparison (== or, in this case, eq) is needed — there is a serious problem in the way the hash %names is populated. These lines:
while (my @row = $sth->fetchrow()) { $names{$row[0]}{$row[1]} = [$row[2],$row[3],$row[4],$row[5]]; }
overwrite the hash entry for $names{$row[0]}{$row[1]} each time a new entry is found, so in the end only the last entry is retained in the hash. Rather than an assignment, you need to push each entry onto an anonymous array:
while (my @row = $sth->fetchrow()) { push @{ $names{ $fields[0] }{ $fields[1] } }, [ @fields[2 .. 5] ]; }
(Note the use of an array slice to reduce the amount of typing required.) This adds another level to the data structure, so you need to be careful when dereferencing. The following example should give you the idea:
use strict; use warnings; my %names = ( X => { A => [ [ qw( Gay Deceiver Head Honcho ) ], [ qw( Chill Blaine Corporate Pawn ) ], [ qw( Tuesday Next Government Agent ) ], [ qw( Harry Hoo Freelance PI ) ], ], B => [ [ qw( Wiley Coyote Acme Addict ) ], [ qw( Gay Divorcee Party Animal ) ], ], }, Y => { A => [ [ qw( Maxwell Smart Agent 86 ) ], ], }, ); for my $key1 (keys %names) { for my $key2 (keys %{ $names{$key1} }) { for my $row_ref (@{ $names{$key1}{$key2} }) { if ($row_ref->[0] eq 'Gay') { print 'Found: ', $row_ref->[0], ' ', $row_ref->[1], "\ +n"; } } } }
Output:
14:21 >perl 1541_SoPW.pl Found: Gay Divorcee Found: Gay Deceiver 14:22 >
By the way, you should always use warnings. And why do the work yourself when the database can do it for you? Why not change your query to something along these lines?
my $sth = $dbh->prepare("SELECT * FROM employees WHERE firstname = 'Gay'" );
:-)
Update: minor edits.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: multi level hash terror - if statement to access specific elements
by Athanasius
in thread multi level hash terror - if statement to access specific elements
by hungrysumo79
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |