$_ considered harmful?

Discussion in 'Perl Misc' started by Larry, Jun 24, 2005.

  1. Larry

    Larry Guest

    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.
     
    Larry, Jun 24, 2005
    #1
    1. Advertisements

  2. Larry

    John Bokma Guest

    You got a warning, now didn't you?
     
    John Bokma, Jun 24, 2005
    #2
    1. Advertisements

  3. Larry

    nobull Guest

    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 *_;
     
    nobull, Jun 25, 2005
    #3
  4. Larry

    nobull Guest

    No he got an error.

    And often failure to localize *_ can cause action at a distance without
    warning.
     
    nobull, Jun 25, 2005
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.