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; } }