http://qs321.pair.com?node_id=833195


in reply to Problem undefining a variable in a loop using a module causing a list to not empty after use of a subroutine

How's this for a totally offtopic response? The snippet of code you show screams "use objects" to me. Really really loudly.

I mean, you have a "Character" that has_some "Classes" and has 'experience' and 'name' and all sorts of other attributes.

You have classes that have experience requirements and various saving throw and THAC0 values by level.

In short, you have big nested data structures with associated behaviors. Using OOP design will help corral the various related stuff into smaller, easier to swallow chunks.

OK, on to the answer to your problems. You have several file scoped lexicals @classes, @THAC0 among them. You push data into them and never clear it out. So if you call print_classes() multiple times, you will keep extending the @classes array forever.

In general, keep all variables in the tightest possible scope and be very wary of global variables (and file scoped lexicals, which are almost the same). For proof of this maxim, if you move the declaration of @classes into the print_classes() routine, your problem will vanish.

When you design a program, one thing you can do to keep things simple is to avoid side-effects in your functions. What this means is that for a given input, you get a given output every time, and nothing else about the program changes.That way, 6 months from now, when your code has become an indispensable tool, and you find a bug, you won't have to remember that foo() must be called before bar() but after whiz(), because they all interact with %whibble, and alter its value.

The OOP stuff helps with this. By tying behaviors to data in neat chunks it makes it easier to partition problems into models that work, while avoiding promiscuous data sharing that leads to spaghetti code.

This looks like a fun project. Happy hacking.


TGI says moo