in reply to Default variable $_ is not getting overwritten

Regardless of how $_ behaves, not using explicit named loop variables is bad coding practice. Well named variables document your code and make it easier to understand, both by you now as you write and debug the code, and by a future stranger with no idea of how the code works (likely a future you) who has to maintain the code.

Do the smart thing, use named variables. You'll thank yourself for it in the future.

Premature optimization is the root of all job security
  • Comment on Re: Default variable $_ is not getting overwritten

Replies are listed 'Best First'.
Re^2: Default variable $_ is not getting overwritten
by Preceptor (Deacon) on Jul 05, 2016 at 09:02 UTC

    Whilst I would generally agree, there's a few places where I consider using $_ to be reasonable. They're mostly the places where I'm not using it explicitly.

    So something like:

    while ( <$input> ) { chomp; my @row = split; #stuff }

    I think is fine, because you _are_ naming it - but still using $_ to preprocess. Likewise sometimes a for loop of the form:

    $_ -> methodcall() for @objects;

    I'm increasingly starting to appreciate it - and as a rule of thumb, if I'm actually _writing_ $_ outside of a single line command (e.g. map/grep/for) then I should be using a named variable.