in reply to Using $_ as a temp var, especially in functions

I would avoid using $_ as a temporary variable, even when localised. Not because it will break your code as it is but because the next coder (or even you some time later) who comes along won't be expecting it and could get bitten.

If the var is so transient that $_ is an OK name for it then, as you say, "my $x;" is shorter to type than "local $_;" :) I would still use a more meaningful name though eg. $temp_foo_counter or $partial_interest_calc etc. If it is distinctly named it is much less likely to cause problems later on.

Update:I read the original node as suggesting using $_ as a generic temporary variable and not necessarily to take advantage of Perl's built in use of $_ as the default target. I have used $_ as converter described and didn't mean to suggest you shouldn't use it for that, though I still advocate taking care :)

--
Life is a tale told by an idiot -- full of sound and fury, signifying nothing. William Shakespeare, Macbeth

  • Comment on Re: Using $_ as a temp var, especially in functions

Replies are listed 'Best First'.
Re: Re: Using $_ as a temp var, especially in functions
by converter (Priest) on Oct 23, 2002 at 04:24 UTC

    Localizing the default pattern-matching space ($_) can make subroutines that perform several pattern-matching or other string operations against the same variable a lot quicker to write and easier to read and maintain.

    I'd rather write:

    local $_ = shift; s/\A[ \t]+//; s/[ \t]+\z//; tr/a-zA-Z0-9//cd; return unless length; ...
    than:
    my $x = shift; $x =~ s/\A[ \t]+//; $x =~ s/[ \t]+\z//; $x =~ tr/a-zA-Z0-9//cd; return unless length $x; ...

    Am I being lazy? Yeah, that's part of it, but it's exactly that sort of idiom (if that even qualifies as idiomatic) that I expect to see in Perl code.

      I would agree that this is, in fact, a very Perly thing to do. Also, it is quite clear what the author intends to do w/ this function, and the localization of $_. I would be afraid of moving too far beyond this little stretch of a pronoun if only to prevent leading the maintainer of the code ( usually me! ) VERY far astray.