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

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.

Replies are listed 'Best First'.
Re: Re: Re: Using $_ as a temp var, especially in functions
by signal9 (Pilgrim) on Oct 23, 2002 at 14:57 UTC
    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.