develooper Front page | perl.perl5.porters | Postings from February 2013

Re: Salvaging lexical $_ from deprecation

Thread Previous | Thread Next
From:
Leon Timmermans
Date:
February 19, 2013 21:38
Subject:
Re: Salvaging lexical $_ from deprecation
Message ID:
CAHhgV8gEm=F2cR1mViR8kOAv86Z-y7zzCD00GAw9cw8ExUzubQ@mail.gmail.com
On Tue, Feb 19, 2013 at 10:14 PM, Jesse Luehrs <doy@tozt.net> wrote:
> On the contrary, $_ is basically useless except for the global form. Or
> are you saying that there shouldn't be any way to implement things like
> Try::Tiny (which does something along the lines of
> "sub catch (&) { local $_ = $@; $_[0]->() }") without using XS? The only
> serious use of $_ I have ever seen (or used personally) is when $_ is
> implicitly localized by some other code (whether that code is perl
> itself in a for loop, or in some other module). This cannot work when $_
> is lexical, and making $_ lexical in fact breaks any code like that.
> "my $_ = 'foo'; my @bar = any { $_ eq 'a' } qw(a b c)" for instance.
> That is why it has been deprecated.

It depends on your goals. In this example:

sub whatever {
    my $_ = shift;
    s/(\d+)/frobnicate($1)/ge;
    s/abc/xyz/g if oh_so_clever();
}

The lexical $_ protects it from any code under frobnicate or
oh_so_clever that forgets to localize $_. In that sense it is useful.

That doesn't mean that it's always what you want (it isn't for any
block function). I'm not sure how to handle that dichotomy though.

Leon

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About