develooper Front page | perl.perl5.porters | Postings from June 2015

Re: extraneous autovivification (foreach (@$x), keys(%$x), ...)

Thread Previous | Thread Next
From:
Eric Brine
Date:
June 30, 2015 16:55
Subject:
Re: extraneous autovivification (foreach (@$x), keys(%$x), ...)
Message ID:
CALJW-qGb7sVXnVcn8A8jGmGw4FK13jjUYC0vaNb8VXBCQP4S=w@mail.gmail.com
On Tue, Jun 30, 2015 at 8:53 AM, Christian Millour <cm.perl@abtela.com>
wrote:

> Hi,
>
> does
>         foreach ( @$x ) { ... }
> really need to autovivify $x to an empty array ref if $x is undef ? In
> other contexts, @$x happily evaluates to an empty list without
> autovivification :
>
> $ perl -MData::Dump -E'dd $x; push @a, @$x; dd $x; frobnicate for @$x; dd
> $x'
> undef
> undef
> []
> $
>
> similarly, keys(%$x) / values(%$x) / each(%$x) autovivify an undef $x to
> an empty hash ref.
>
> Do these autovivifications have a purpose or could they be be avoided /
> optimized away ?
>
> TIA,
>
> --Christian
>

The difference between foreach and push is that foreach imposes an lvalue
context on its list and push does not.

foreach needs to do this so you can do << $_ = uc($_) for @names; >>. <<
sub foo { } foo(@$x) >> will similarly evaluate @$x as an lvalue context,
autovivifying $x.

I realize this doesn't answer your question.

- Eric

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