$_ considered harmful?

L

Larry

I just had my script die with "Attempt to modify read-only value"
(intermittently) on a line that was simply doing:

while (<$inf>) { ... $_ ... }

I did some googling and it seems that this error can happen in cases
where the last time you used $_ it was bound to a variable that you no
longer have the permission to modify. In my particular script, the
problem was ocurring in code that had just done a fork, so it's
probably related to that. I fixed it by changing it to:

while (my $line = <$inF>) { ... $line ... }

My point is that this seems to be a big argument for not using $_.
It's such a commonly used (and convenient) part of the language... it's
disconcerting to find that it's apparently somewhat dangerous.
 
J

John Bokma

Larry said:
It's such a commonly used (and convenient) part of the language... it's
disconcerting to find that it's apparently somewhat dangerous.

You got a warning, now didn't you?
 
N

nobull

Larry said:
I just had my script die with "Attempt to modify read-only value"
(intermittently) on a line that was simply doing:

while (<$inf>) { ... $_ ... }
My point is that this seems to be a big argument for not using $_.
It's such a commonly used (and convenient) part of the language... it's
disconcerting to find that it's apparently somewhat dangerous.

It's not IMNSHO an argument against $_ per se but rather one against
using the magic while(<FILE>) construct.

Still I find while(<FILE>) so convenient that I'm prepared to pay the
price of typing

local *_;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top