http://qs321.pair.com?node_id=11120302


in reply to Shouldn't LITERAL references be readonly? (updated)

The literal reference is just a value which in your map just happens to be contained in $_. When you reassign 1 to it, it's not changing the reference in any way, you're just putting something else in $_ (although this is where I'm getting fuzzy and agree it's somewhat weird); it's just that $_ just happens to be aliased to some temporary SV* / SVrv that the map is using as its argument list. The assignment isn't changing the referenced value, it's just sticking the new SViv 1 into that SV*.

DB<1> $a = $b = [qw/a b c/] DB<2> x map { $_ = 1 } $a 0 1 DB<3> x $a 0 1 DB<4> x $b 0 ARRAY(0x7fa8144335b0) 0 'a' 1 'b' 2 'c'

Hopefully someone more conversant in perlguts than I might can explain it better.

The cake is a lie.
The cake is a lie.
The cake is a lie.

Replies are listed 'Best First'.
Re^2: Shouldn't references be readonly?
by LanX (Saint) on Aug 05, 2020 at 02:04 UTC
    please compare
    DB<30> x map { $_ = 1 } 2 Modification of a read-only value attempted at (eval 40)[c:/Perl_524/l +ib/perl5db.pl:737] line 2. DB<31>

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

Re^2: Shouldn't references be readonly?
by LanX (Saint) on Aug 05, 2020 at 17:13 UTC
    > The literal reference is just a value which in your map just happens to be contained in $_.

    I think you are trying to say that references are not aliased but copied in "aliasing situations" to avoid some overhead...

    But if you look at the following results you will notice that the ref of an alias is still identical while the ref of a copy isn't. (I used @R to keep the refcount up and hence avoid the reuse of freed addresses)

    DB<55> @R= map { \$_ } $a DB<56> x @R 0 REF(0x31fae58) # -> ARRAY(0x3353230) empty array DB<57> x \$a 0 REF(0x31fae58) # same -> ARRAY(0x3353230) empty array DB<58> $b=$a DB<59> x \$b 0 REF(0x3353a58) # different -> ARRAY(0x3353230) empty array DB<60>

    DB<64> p \$a == $R[0] 1 DB<65> p \$a == \$b DB<66>

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery