|XP is just a number|
Next from inner loop only works "most of the time"by Marshall (Canon)
|on May 18, 2021 at 12:31 UTC||Need Help??|
Marshall has asked for the wisdom of the Perl Monks concerning the following question:
I wrote some code today that worked most of the time but not all of the time -> different runs of Perl produced different results.
I have fixed the code so that it is reliable. My question is "what happens inside Perl such that my first version was unreliable?"
I started playing a scrabble like game on my cellphone and once I got to level 108, things got hard. So I whipped out a cheater program! Pretty easy to do and my quick hack worked fine except that it made mistakes but only some of the time.
Here is the output of a "good" run:
The letters "otrwreh" are its "vocabulary" for forming words. "r" can be repeated, but none of the other letters.
The pattern "---w", means show all 4 letter words in the dictionary that end in "w" that are formed using only the letters "otrweh".
All well and good until I saw this run:
Ok, the offending unreliable code snippet:
Once the regex does its thing on a huge list of possible words, I take out any results where a letter occurs more often in the result than in the pattern list of characters. so, "whew" should get thrown away. But evidently the next is not being executed. Sometimes the code falls through the loop and "whew" gets printed even though "w" occurs too often for the "rules".
Now arguably using "next" in this way is not the brightest thing I've done. But when hacking, stuff happens and sometimes I try something new with Perl. This was just "throw away" code for my own amusement.
Of course I rewrote the code using a more traditional approach like this:
So, I get the answer of "hey, don't do that!". I am curious why my hack was unreliable? It worked often enough that I figured that it was ok, until problems showed up later on. I had never used next in this way, although I have used a labeled redo before.
Update: Now that I think about it, it could be that using the default variable $_ in both loops could be an issue. I normally would assign an explicit my variable for the loop variable. But in quick, just barf if out code, that didn't happen here.