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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |