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

[perl #133064] Multiple assignments in assignment ops

Thread Previous
From:
Daniel Perrett
Date:
April 5, 2018 20:39
Subject:
[perl #133064] Multiple assignments in assignment ops
Message ID:
rt-4.0.24-31313-1522946911-1342.133064-75-0@perl.org
# New Ticket Created by  Daniel Perrett 
# Please include the string:  [perl #133064]
# in the subject line of all future correspondence about this issue. 
# <URL: https://rt.perl.org/Ticket/Display.html?id=133064 >


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}'
0

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

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'
b

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.

Daniel


--
 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


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