in reply to Re: foreach within a foreach
in thread foreach within a foreach

Well, I did as you suggested, shotgunefx:  I added a print statement after the first line of the inner foreach statement and set up place holders.  The result was that I could see the employee id printed five times (once for each weekday record) for each employee.  So the inner foreach statement does seem to be getting the employee id numbers.

I tested a little further by printing out @schedule at the end of the inner loop and I ended up with data displayed that was lengthier with each looping.  It turns out that the problem was with a push statement that I didn't copy into my posting.  In an attempt to shorten my posting to make it easier to discuss, I didn't re-type my code accurately.   The last line I presented in the inner loop reads on the posting as follows:

@schedule = $sth->fetchrow_array();

In actuallity it reads in my script like this:

@_ = $sth->fetchrow_array(); push(@schedule, @_);

The problem is that the first employee has nothing scheduled because she's on vacation this week.  And since I'm appending the array for each record and not resetting it after each inner loop, each employee looks like they have nothing scheduled.

I've gone back and added @schedule = ""; to the line just above the inner loop and it now works.  Sorry I didn't post that last line correctly--as I said I was looking for brevity in the code at least.  Thanks for the troubleshooting suggestion regarding putting print statements in the inner loop.  That brought the whole thing to light.

That's Spenser, with an "s" like the detective.

Replies are listed 'Best First'.
Re: Re: Re: foreach within a foreach
by shotgunefx (Parson) on Jun 07, 2002 at 22:36 UTC
    Glad I could help. A couple comments though, you probably want to initilize @schedule with an empty list.
    @schedule = ();

    The other is you usually don't want to assign to @_, depending on the context it might cause subtle bugs. @_ has some magic associated with it. For instance, in a sub, @_ acts as aliases to the passed arguments. (Example below)

    It appears assigning to @_ makes it lose it's magic so I don't think it is a problem here but it's probably a dubious habit to form.

    #!/usr/bin/perl -w use strict; my ($foo,$bar,$baz) = (1,2,3); print "$foo, $bar, $baz \n"; # Prints 1, 2, 3 foo($foo,$bar,$baz); print "$foo, $bar, $baz \n"; # Prints 5, 10 , 15 sub foo { foreach (@_) { $_ *= 5; } }
    -Lee

    "To be civilized is to deny one's nature."