Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Variable being clobbered by a seemingly unrelated while loop

by blindluke (Hermit)
on Oct 08, 2014 at 06:35 UTC ( [id://1103138]=note: print w/replies, xml ) Need Help??


in reply to Variable being clobbered by a seemingly unrelated while loop

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1103138]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-16 16:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found