Loop not ending, insight as to why?

L

LANkrypt0

I wrote the following code and for some reason it does not exit when my
$word is the same as $ARGV[0].

Can anyone shed some light on this for me?
Is it because it needs to actually run through every foreach loop?

Thanks

==+ BEGIN CODE +==

#!/usr/bin/perl
use strict;

my @valpha = ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
my $word;

until ($word eq $ARGV[0])
{
foreach my $letter1 (@valpha)
{
foreach my $letter2 (@valpha)
{
foreach my $letter3 (@valpha)
{
foreach my $letter4 (@valpha)
{
foreach my $letter5 (@valpha)
{
$word = $letter1.$letter2.$letter3.$letter4.$letter5;
print "$word\n";
}
}
}
}
}
}
print "Word found!\n";

==+ END CODE +==
 
J

Jürgen Exner

LANkrypt0 said:
I wrote the following code and for some reason it does not exit when
my $word is the same as $ARGV[0].

Can anyone shed some light on this for me?
Is it because it needs to actually run through every foreach loop?

Thanks

==+ BEGIN CODE +==

#!/usr/bin/perl
use strict;

my @valpha = ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y",
"z"); my $word;

until ($word eq $ARGV[0])
{
foreach my $letter1 (@valpha)
{
foreach my $letter2 (@valpha)
{
foreach my $letter3 (@valpha)
{
foreach my $letter4 (@valpha)
{
foreach my $letter5 (@valpha)
{
$word = $letter1.$letter2.$letter3.$letter4.$letter5;
print "$word\n";
}
}
}
}
}
}
print "Word found!\n";

==+ END CODE +==

You got your program logic totally messed up.
For the sake of argument imagine that the "until" does not exist.
Now, how often is the outermost "foreach" being executed? Or to rephrase the
question, what would be the last letter, that is processed by the outermost
loop?

The same logic applies to the inner loops, too, which ultimately means that
$word has a value of "zzzzz" when the outermost foreach terminates.

Only now after all the inner loops are done will the "until" have a chance
to kick in and to check if the condition is satisfied. Obviously it is not
(unless you program argument happens to be "zzzzz").
Therefore the whole foreach loop chaos starts over again.

jue
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top