develooper Front page | perl.perl5.porters | Postings from April 2018

[perl #133064] Multiple assignments in assignment ops

Thread Previous
Daniel Perrett
April 5, 2018 20:39
[perl #133064] Multiple assignments in assignment ops
Message ID:
# New Ticket Created by  Daniel Perrett 
# Please include the string:  [perl #133064]
# in the subject line of all future correspondence about this issue. 
# <URL: >

The following are not equivalent, which I found surprising:

$ perl -wle 'my $foo = {}; $foo->{b} = defined $foo->{b} ? $foo->{b} : scalar keys %$foo; print $foo->{b}'

$ perl -wle 'my $foo = {}; $foo->{b} //= scalar keys %$foo; print $foo->{b}'

Assignment operators other than '=' all appear to, in effect, assign the lvalue to undef first (if it does not exist); only then is the new value calculated... a bit like autovivification. This can be confirmed by jumping out of the operation before it completes:

$ perl -wle 'my $foo = {}; for (1) { $foo->{b} += 1 + next; } print for keys %$foo'

This seems like one of those apparent 'bugs' for which there is a good and interesting reason... but I would have expected to find this behaviour made clear somewhere in the documentation on perlop or, failing that, perlref, and I cannot see it. Is it intentional?

I tested on v5.18.2 v5.22.4 which I happened to have lying around at the time and did not find anything relevant in the major perldeltas since then.


 The Wellcome Sanger Institute is operated by Genome Research
 Limited, a charity registered in England with number 1021457 and a
 company registered in England with number 2742969, whose registered
 office is 215 Euston Road, London, NW1 2BE.

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