$_ considered harmful?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

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.

Re: $_ considered harmful?

Quoted text here. Click to load it

You got a warning, now didn't you?

John                   Small Perl scripts: http://johnbokma.com/perl/
               Perl programmer available:     http://castleamber.com/
            Happy Customers: http://castleamber.com/testimonials.html

Re: $_ considered harmful?

John Bokma wrote:
Quoted text here. Click to load it

No he got an error.

And often failure to localize *_ can cause action at a distance without

Re: $_ considered harmful?

Larry wrote:

Quoted text here. Click to load it

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 *_;

Site Timeline