$_ 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. Advertising

  2. Larry

    John Bokma Guest

    John Bokma, Jun 24, 2005
    #2
    1. Advertising

  3. Larry

    Guest

    Larry wrote:

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

    Guest

    John Bokma wrote:
    > "Larry" <> wrote:
    >
    > > 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?


    No he got an error.

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

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Robert Mischke
    Replies:
    3
    Views:
    1,522
    Tony Morris
    May 19, 2005
  2. Toby A Inkster
    Replies:
    19
    Views:
    740
  3. Andy Dingley

    XTech conference considered harmful?

    Andy Dingley, Feb 13, 2006, in forum: HTML
    Replies:
    2
    Views:
    589
    Richard Sexton
    Feb 14, 2006
  4. Replies:
    25
    Views:
    1,307
    Isaac To
    Oct 31, 2003
  5. Replies:
    9
    Views:
    531
Loading...

Share This Page