Syntactic Confectionery Delight | |
PerlMonks |
Re: Final Print Statement in Foreach Loop Prints Twiceby haukex (Archbishop) |
on Nov 11, 2018 at 08:44 UTC ( [id://1225566]=note: print w/replies, xml ) | Need Help?? |
Hello ScarletRoxanne, welcome to PerlMonks and Perl! See #4 on the Basic debugging checklist: print your data structures. For example, if I add use Data::Dump; dd \%anaHash; just after the first loop, and enter Hello and World, the output I get is:
Whereas if I enter restful and fluster, I get:
Now if you look at your second loop, you're iterating over values %anaHash, so I hope it becomes clear why the loop is executing twice? I'm not exactly sure about what your requirements are, but I'm not sure why you need the second loop? Checking that the phrases are identical could be done with eq on $aWord and $bWord, and whether or not the words are anagrams could be checked by looking at the number of keys in the hash, no? Some more general tips:
I can't get the script to print FALSE by, for example, setting a variable to '' or 0, etc. or saying return ''. Ideally, I wouldn't have to put "print TRUE/FALSE" in the script at all. I'm not sure what you mean by this - Perl doesn't have any "TRUE" and "FALSE" constants like other languages, instead there are simply a couple of values that Perl interprets as being "false" in a "boolean context" (for example, in an if (...) condition) - see Truth and Falsehood. These values don't get converted internally into anything else. If you want Perl to print the strings TRUE and FALSE, you'll need to tell it to do that, such as in print $value?"TRUE":"FALSE". I'm curious why my m// expression doesn't work. If I enter hello and hell o, then the regular expressions will be / +hello/ and / +hell o/. Because both of them require spaces before the h, which neither of the input strings have, neither regex will match. I suspect you may have wanted to match on the keys instead, but even then, I think you need to rethink the overall approach, because there would still be further modifications needed to make it work with regexes. (Hint: I would've made a copy of the strings and removed all the spaces.) Another regex tip: If you don't anchor your regular expressions with ^ and $, then remember that the regular expression will match anywhere in the string (e.g. "foobar"=~/a/ is true). Update 2019-08-17: Updated the link to "Truth and Falsehood".
In Section
Seekers of Perl Wisdom
|
|