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

Re: Salvaging lexical $_ from deprecation

Thread Previous | Thread Next
Leon Timmermans
February 19, 2013 21:38
Re: Salvaging lexical $_ from deprecation
Message ID:
On Tue, Feb 19, 2013 at 10:14 PM, Jesse Luehrs <> 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/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.


Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About