First of all, your code runs with strict and warnings enabled, no need to comment them out.

The magic $_ variable is an alias, not a copy. This can be useful when you are iterating over an array (with for (@array)), and modifying $_ - you will see that the array elements will change.

In your code, the $runlvl variable is clobbered when the while loop starts. You can test this by changing it to a read only value:

for ('23') { /2/ and process($0); /3/ and finalize(); }

Now, even without strict and warnings, you will see:

Modification of a read-only value attempted at ./test.pl line 9.

...which corresponds to the beginning of the while loop. The easiest solution would be to change the $_ to a named alias, as in:

for my $switch ($runlvl) { $switch =~ /2/ and process($0); $switch =~ /3/ and finalize(); }

There is a very good explanation of the default scalar variable, and the behavior that you are experiencing, in the Modern Perl book (here), which says:

As English gets confusing when you have too many pronouns and antecedents, so does Perl when you mix explicit and implicit uses of $_. If you use it in multiple places, one piece of code may silently override the value expected by another piece of code. For example, if one function uses $_ and you call it from another function which uses $_, the callee may clobber the caller's value.

regards,
Luke Jefferson


In reply to Re: Variable being clobbered by a seemingly unrelated while loop by blindluke
in thread Variable being clobbered by a seemingly unrelated while loop by texh

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.