Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Here's a two question SOPW that I've been working on this morning.

The code below had some code removed to make it easier to follow. I'm trying to loop over the chunk until I have twice as many pictures as I asked it to find. It finds pictures, lots of them, but doesn't STOP finding them once it goes over 2X.

I know it's finding enough because I'm printing $pics_found each time through and it's way, way high.

If someone can fix THIS problem for me, that'd be great. Else I tried to do a workaround by adding a conditional near the top of the loop if ($pics_found >= $pics_to_find * 2). I tried using last and it kept going over and over again (it never found more pictures but it printed out Finished finding... forever. I then added exit and it then, well, exitted the whole script. How do I make the conditional make the while() stop?

while($pics_found <= $pics_to_find * 2) { foreach my $gal (@gals) { if ($pics_found >= $pics_to_find * 2) { print "\nFinished finding enough pictures ($pics_found)."; exit; } $pics_found = $#pics + 1; print "\nMoving on to next gallery. Currently found $pics_found +pics"; } if ($pics_found < $pics_to_find * 2) { print "We ran out of pictures to find for this search query."; last; } }

Replies are listed 'Best First'.
Re: while loop not stopping
by johngg (Canon) on May 16, 2007 at 15:34 UTC
    This line

    $pics_found = $#pics + 1;

    looks a bit odd. I don't see a @pics array anywhere (perhaps it got lost when cutting your code down for the post) but I assume that is where you hope to store the pictures you've found. You would probably do better to initialise $pics_found before your loop then increment it ($pics_found ++;) every time you find a picture and put it in the @pics array (assuming that's what you are doing).

    Cheers,

    JohnGG

Re: while loop not stopping
by ropey (Hermit) on May 16, 2007 at 15:25 UTC

    Your last will only apply the looped it is scoped in, which in this case is your while loop... not your foreach loop.

    The following simply ends the looping when it finds twice your '$pics_to_find'.... maybe easier to read at a leter stage to add a variable '$max_pics' instead of always multiplying by 2 everytime.

    my $max_pics = $pics_to_find * 2; my $pics_found = 0; foreach my $gal(@gals) { last if($pics_found >= $max_pics); $pics_found++; } print "Found what I wanted " if($pics_found >= $max_pics);
Re: while loop not stopping
by swampyankee (Parson) on May 16, 2007 at 15:44 UTC

    Where do you populate @pics? From the code fragment you supplied, @pics never has anything inserted into it.

    emc

    Insisting on perfect safety is for people who don't have the balls to live in the real world.

    —Mary Shafer, NASA Dryden Flight Research Center