Lexical scoping exists to make your life easier. You don't need to reset variables if you use lexical scoping to your advantage. Here's a very concise example:

use strict; use warnings; my $i = 0; while( $i++ < 10 ) { no warnings qw/uninitialized/; my $scoped; print "\$scoped contains $scoped\n"; $scoped = 100; }

This snippet uses strict and warnings, but for the purposes of this particular demonstration turns off the "uninitialized value" warning. Next, it loops ten times. Each time, it creates a lexically scoped (my) variable called $scope. It prints that variable's contents (which are essentially empty, or undefined). It then assigns the number 100 to $scoped, and loops. If you weren't using lexical scoping, on the second loop iteration, $scoped would still contain 100, and that would print. But as you see if you run this, on each iteration $scoped is still empty. Why? Because at the end of each while block iteration, the lexical variable named $scoped "falls out of scope" (it disappears, forever gone). And on the next iteration, a new one is created (via 'my').

What you need to do is write your script in such a way that when the player decides to play again, all the variables that need to be reset simply fall out of scope. The ones whos values should be kept would need to have been defined at a broader scope.

This sort of thing is described in perlintro, perlsub and perlsyn, for starters. Therein you'll also read about properly passing parameters to subroutines rather than absorbing values through global osmosis. Welcome to a new way of thinking.


Dave


In reply to Re: Resetting variables by davido
in thread Resetting variables by yacoubean

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.