Changing the values of $i and $counter within the loop does not look like a good idea to me.
If I've understood you correctly you want to loop through values 1 - 100, checking whether each value is in @numbers. If it is then you want to display an image corresponding to that number, and if it is not then you display an error image.
If this is what you want then you don't need both loops if @numbers is sorted in ascending numerical order:
#!/usr/bin/perl -w use strict; my @numbers = (1, 2, 5, 7, 8, 9); my $pos = 0; for my $counter (1..10) { # Is this value of $counter the next value in @numbers? # If it is then display image number $counter and move onto the # next value in @numbers. # If it is not then display the error image and carry on looking # for the same value in @numbers. if (defined $numbers[$pos] and $numbers[$pos] == $counter) { print "Use image: $counter \n"; $pos++; } else { print "Use error image\n"; } }
Update: I think this is what you were trying to write. This does not depend on the values in @numbers being sorted:
#!/usr/bin/perl -w use strict; my @numbers = (1, 2, 5, 7, 8, 9); for my $counter ( 1..10 ) { my $img; # Check whether this value of counter is in @numbers for my $i ( @numbers ) { if ($i == $counter) { $img = "image" . ($counter-1); last; } } # If $img is still undefined then this value is missing if (!defined $img) {$img = "error.bmp"} print "$counter $img\n"; }
In reply to Re: Real confusion with loops and counters
by Bilbo
in thread Real confusion with loops and counters
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |