Spenser has asked for the wisdom of the Perl Monks concerning the following question:
I have what I think is a scoping problem with a set of two foreach statements. I have two tables in mySQL: one with employee info., in particular employee id's and employee names; the other table has information on each employee's work schedule for each day. I'm trying to loop through the list of employees and then for each employee, loop through the schedule records for each day relavent to each employee. Note, there are only five records for each employee since we only schedule one work week at a time.
Below is an excerpt of my code. I tried to cut it down to only the relevant pieces. So, please fill in the missing pieces with your imagination.
# After the initial, usual stuff I query mySQL using # DBI and extract employee id numbers and their names # for an array and a hash. while (@emp_list = $sth->fetchrow_array()) { push(@emps, $emp_list[0]); $employees{$emp_list[0]} ="$emp_list[1]"; } $sth->finish(); my @days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri'); foreach $emp_id(@emps) { print "Employee: ", $employees{$emp_id}, "\n"; print "Employee ID: ", $emp_id, "\n"; foreach $wkday(@days) { $sql_str = "SELECT emp_name, field2, field3 FROM table1 WHERE emp_id='$emp_id' AND wkday='$wkday'"; $sth= $dbh->prepare($sql_str); $sth->execute(); @schedule = $sth->fetchrow_array(); } print @schedule; # Actually I break the @schedule up nicer than this. }
The problem seems to be that the value of the variable $emp_id does not penetrate the second or inner foreach loop. The result is that $emp_id for the loop regarding the schedule is blank, although the $emp_id does print on the header line above it. How do I pass the value of a variable (e.g., $emp_id) of one foreach loop onto another foreach loop?
That's Spenser, with an "s" like the detective.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: foreach within a foreach
by shotgunefx (Parson) on Jun 07, 2002 at 19:32 UTC | |
by Silicon Cactus (Scribe) on Jun 07, 2002 at 19:54 UTC | |
by tadman (Prior) on Jun 07, 2002 at 20:02 UTC | |
by Silicon Cactus (Scribe) on Jun 10, 2002 at 14:40 UTC | |
by dsheroh (Monsignor) on Jun 07, 2002 at 20:06 UTC | |
by shotgunefx (Parson) on Jun 07, 2002 at 20:04 UTC | |
by Spenser (Friar) on Jun 07, 2002 at 20:53 UTC | |
by shotgunefx (Parson) on Jun 07, 2002 at 22:36 UTC | |
|
Re: foreach within a foreach
by rbc (Curate) on Jun 07, 2002 at 21:15 UTC | |
by Spenser (Friar) on Jun 07, 2002 at 21:51 UTC |